-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.py
More file actions
1085 lines (772 loc) · 43.4 KB
/
plugin.py
File metadata and controls
1085 lines (772 loc) · 43.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
import json
import math
import os
import datetime
from swift.plugin import ORM, orms
from swift.utils import get_logger
logger = get_logger()
class PromptFormatORM(ORM):
def __call__(self, completions, **kwargs) -> list[float]:
import re
import json
basic_pattern = r"<think>[\s\S]*?</think>\s*<answer>[\s\S]*?</answer>"
rewards = []
for content in completions:
reward = 0.0
if re.search(basic_pattern, content, re.DOTALL):
reward += 0.5
try:
answer_match = re.search(r"<answer>\s*([\s\S]*?)\s*</answer>", content, re.DOTALL)
if answer_match:
answer_content = answer_match.group(1).strip()
code_block_json = re.search(r"```(?:json)?\s*(\{[\s\S]*?\})\s*```", answer_content, re.DOTALL)
if code_block_json:
json_str = code_block_json.group(1)
else:
json_match = re.search(r"(\{[\s\S]*?\})", answer_content, re.DOTALL)
json_str = json_match.group(1) if json_match else None
if json_str:
try:
json_obj = json.loads(json_str)
if self._validate_scene_classification(json_obj) or self._validate_fraud_classification(json_obj) or self._validate_fraud_type_classification(json_obj):
reward += 0.5
except json.JSONDecodeError:
cleaned_json = re.sub(r'[\n\r\t]', ' ', json_str)
try:
json_obj = json.loads(cleaned_json)
if self._validate_scene_classification(json_obj) or self._validate_fraud_classification(json_obj) or self._validate_fraud_type_classification(json_obj):
reward += 0.5
except:
pass
except Exception as e:
pass
after_answer = content.split("</answer>")[-1].strip()
if after_answer and after_answer != "\n":
if len(after_answer) > 1:
reward -= (len(after_answer)-1) * 0.001
else:
reward -= len(after_answer) * 0.001
rewards.append(reward)
return rewards
@staticmethod
def _validate_scene_classification(json_obj):
required_keys = {"conversation_stage", "scene", "reason", "confidence"}
return (
all(key in json_obj for key in required_keys)
and isinstance(json_obj.get("conversation_stage"), str)
and (isinstance(json_obj["scene"], str) or json_obj["scene"] is None)
and isinstance(json_obj["reason"], str)
and isinstance(json_obj["confidence"], (int, float))
and 0 <= json_obj["confidence"] <= 1
)
@staticmethod
def _validate_fraud_classification(json_obj):
required_keys = {"conversation_stage", "is_fraud", "reason", "confidence"}
return (
all(key in json_obj for key in required_keys)
and isinstance(json_obj.get("conversation_stage"), str)
and (isinstance(json_obj["is_fraud"], bool) or json_obj["is_fraud"] is None)
and isinstance(json_obj["reason"], str)
and isinstance(json_obj["confidence"], (int, float))
and 0 <= json_obj["confidence"] <= 1
)
@staticmethod
def _validate_fraud_type_classification(json_obj):
required_keys = {"conversation_stage", "fraud_type", "reason", "confidence"}
return (
all(key in json_obj for key in required_keys)
and isinstance(json_obj.get("conversation_stage"), str)
and (isinstance(json_obj["fraud_type"], str) or json_obj["fraud_type"] is None)
and isinstance(json_obj["reason"], str)
and isinstance(json_obj["confidence"], (int, float))
and 0 <= json_obj["confidence"] <= 1
)
class NewSceneClassificationORM(ORM):
def __call__(self, completions, answers, conversation_stage, **kwargs) -> list[float]:
import os
import re
import json
import datetime
base_reward = 5.0
base_penalty = -3.0
ALLOWED_SCENES = ["订餐服务", "咨询客服", "预约服务", "交通咨询", "日常购物", "打车服务", "外卖服务", None]
rewards = []
current_logs = []
call_timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
audio_indices = kwargs.get("audio_idx", [1]*len(completions))
audio_lengths = kwargs.get("audio_length", [1]*len(completions))
for content, ans, sta, audio_idx, audio_len in zip(completions, answers, conversation_stage, audio_indices, audio_lengths):
reward = 0.0
log_entry = {
"timestamp": call_timestamp,
"answer": ans,
"response": content,
"error": None,
"reward": 0.0,
"details": {
"audio_idx": audio_idx,
"audio_length": audio_len
}
}
try:
answer_text = re.search(r"<answer>\s*(.*?)\s*</answer>", content, re.DOTALL)
if not answer_text:
rewards.append(0.0)
log_entry["error"] = "No answer tag found"
current_logs.append(log_entry)
continue
answer_content = answer_text.group(1).strip()
code_block_match = re.search(r"```(?:json)?\s*(\{[\s\S]*?\})\s*```", answer_content, re.DOTALL)
if code_block_match:
json_str = code_block_match.group(1)
else:
json_match = re.search(r"(\{.*\})", answer_content, re.DOTALL)
if json_match:
json_str = json_match.group(1)
else:
rewards.append(0.0)
log_entry["error"] = "No JSON object found in answer"
current_logs.append(log_entry)
continue
try:
json_obj = json.loads(json_str)
log_entry["details"]["parsed_json"] = json_obj
except json.JSONDecodeError:
cleaned_json = re.sub(r'[\n\r\t]', ' ', json_str)
try:
json_obj = json.loads(cleaned_json)
log_entry["details"]["parsed_json"] = json_obj
log_entry["details"]["json_required_cleaning"] = True
except:
rewards.append(0.0)
log_entry["error"] = "JSON parsing failed after cleaning"
current_logs.append(log_entry)
continue
scene = json_obj.get("scene")
reason = json_obj.get("reason")
log_entry["details"]["scene"] = scene
log_entry["details"]["reason"] = reason
log_entry["details"]["response_type"] = "json"
if scene not in ALLOWED_SCENES and scene is not None:
reward = base_penalty
log_entry["details"]["classification_valid"] = False
log_entry["details"]["punishment"] = reward
log_entry["details"]["punishment_reason"] = f"Scene '{scene}' not in allowed list: {ALLOWED_SCENES}"
rewards.append(reward)
log_entry["reward"] = reward
current_logs.append(log_entry)
continue
log_entry["details"]["classification_valid"] = True
if scene == ans:
reward = base_reward
log_entry["details"]["classification_correct"] = True
elif scene is None and sta == "early_stage":
reward = base_reward
else:
reward = 0
log_entry["details"]["classification_correct"] = False
except Exception as e:
log_entry["error"] = f"Error processing response: {str(e)}"
rewards.append(reward)
log_entry["reward"] = reward
current_logs.append(log_entry)
try:
log_dir = os.path.join(".", "logs", "new_scene_classification_reward_func")
os.makedirs(log_dir, exist_ok=True)
hour_timestamp = datetime.datetime.now().strftime("%Y%m%d_%H")
log_file = os.path.join(log_dir, f"log_{hour_timestamp}.json")
existing_logs = []
if os.path.exists(log_file):
try:
with open(log_file, 'r', encoding='utf-8') as f:
existing_logs = json.load(f)
except (json.JSONDecodeError, UnicodeError):
existing_logs = []
existing_logs.extend(current_logs)
with open(log_file, 'w', encoding='utf-8') as f:
json.dump(existing_logs, f, ensure_ascii=False, indent=2)
except Exception as e:
print(f"Error writing log file: {str(e)}")
return rewards
class NewFraudClassificationORM(ORM):
def __call__(self, completions, answers, conversation_stage, **kwargs) -> list[float]:
import os
import re
import json
import datetime
base_reward = 5.0
base_penalty = -3.0
rewards = []
current_logs = []
call_timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
audio_indices = kwargs.get("audio_idx", [1]*len(completions))
audio_lengths = kwargs.get("audio_length", [1]*len(completions))
for content, ans, sta, audio_idx, audio_len in zip(completions, answers, conversation_stage, audio_indices, audio_lengths):
reward = 0.0
log_entry = {
"timestamp": call_timestamp,
"answer": ans,
"response": content,
"error": None,
"reward": 0.0,
"details": {
"audio_idx": audio_idx,
"audio_length": audio_len
}
}
try:
answer_text = re.search(r"<answer>\s*(.*?)\s*</answer>", content, re.DOTALL)
if not answer_text:
rewards.append(0.0)
log_entry["error"] = "No answer tag found"
current_logs.append(log_entry)
continue
answer_content = answer_text.group(1).strip()
code_block_match = re.search(r"```(?:json)?\s*(\{[\s\S]*?\})\s*```", answer_content, re.DOTALL)
if code_block_match:
json_str = code_block_match.group(1)
else:
json_match = re.search(r"(\{.*\})", answer_content, re.DOTALL)
if json_match:
json_str = json_match.group(1)
else:
rewards.append(0.0)
log_entry["error"] = "No JSON object found in answer"
current_logs.append(log_entry)
continue
try:
json_obj = json.loads(json_str)
log_entry["details"]["parsed_json"] = json_obj
except json.JSONDecodeError:
cleaned_json = re.sub(r'[\n\r\t]', ' ', json_str)
try:
json_obj = json.loads(cleaned_json)
log_entry["details"]["parsed_json"] = json_obj
log_entry["details"]["json_required_cleaning"] = True
except:
rewards.append(0.0)
log_entry["error"] = "JSON parsing failed after cleaning"
current_logs.append(log_entry)
continue
is_fraud = json_obj.get("is_fraud")
log_entry["details"]["is_fraud"] = is_fraud
log_entry["details"]["response_type"] = "json"
if not isinstance(is_fraud, bool) and is_fraud is not None:
reward = base_penalty
log_entry["details"]["is_fraud_valid"] = False
log_entry["details"]["punishment"] = reward
log_entry["details"]["punishment_reason"] = f"is_fraud must be a boolean value (true/false), got {type(is_fraud).__name__}: {is_fraud}"
rewards.append(reward)
log_entry["reward"] = reward
current_logs.append(log_entry)
continue
log_entry["details"]["is_fraud_valid"] = True
if (is_fraud is True and ans == "fraud") or (is_fraud is False and ans == "normal"):
reward = base_reward
log_entry["details"]["classification_correct"] = True
elif is_fraud is None and sta == "early_stage":
reward = base_reward
else:
reward = 0
log_entry["details"]["classification_correct"] = False
except Exception as e:
log_entry["error"] = f"Error processing response: {str(e)}"
rewards.append(reward)
log_entry["reward"] = reward
current_logs.append(log_entry)
try:
log_dir = os.path.join(".", "logs", "new_fraud_classification_reward_func")
os.makedirs(log_dir, exist_ok=True)
hour_timestamp = datetime.datetime.now().strftime("%Y%m%d_%H")
log_file = os.path.join(log_dir, f"log_{hour_timestamp}.json")
existing_logs = []
if os.path.exists(log_file):
try:
with open(log_file, 'r', encoding='utf-8') as f:
existing_logs = json.load(f)
except (json.JSONDecodeError, UnicodeError):
existing_logs = []
existing_logs.extend(current_logs)
with open(log_file, 'w', encoding='utf-8') as f:
json.dump(existing_logs, f, ensure_ascii=False, indent=2)
except Exception as e:
print(f"Error writing log file: {str(e)}")
return rewards
class NewFraudTypeClassificationORM(ORM):
def __call__(self, completions, answers, conversation_stage, **kwargs) -> list[float]:
import os
import re
import json
import datetime
base_reward = 5.0
base_penalty = -3.0
ALLOWED_FRAUD_TYPES = ["投资诈骗", "钓鱼诈骗", "身份盗窃", "彩票诈骗", "银行诈骗", "绑架诈骗", "客服诈骗", "邮件诈骗"]
rewards = []
current_logs = []
call_timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
audio_indices = kwargs.get("audio_idx", [1]*len(completions))
audio_lengths = kwargs.get("audio_length", [1]*len(completions))
for content, ans, sta, audio_idx, audio_len in zip(completions, answers, conversation_stage, audio_indices, audio_lengths):
reward = 0.0
log_entry = {
"timestamp": call_timestamp,
"answer": ans,
"response": content,
"error": None,
"reward": 0.0,
"details": {
"audio_idx": audio_idx,
"audio_length": audio_len
}
}
try:
answer_text = re.search(r"<answer>\s*(.*?)\s*</answer>", content, re.DOTALL)
if not answer_text:
rewards.append(0.0)
log_entry["error"] = "No answer tag found"
current_logs.append(log_entry)
continue
answer_content = answer_text.group(1).strip()
code_block_match = re.search(r"```(?:json)?\s*(\{[\s\S]*?\})\s*```", answer_content, re.DOTALL)
if code_block_match:
json_str = code_block_match.group(1)
else:
json_match = re.search(r"(\{.*\})", answer_content, re.DOTALL)
if json_match:
json_str = json_match.group(1)
else:
rewards.append(0.0)
log_entry["error"] = "No JSON object found in answer"
current_logs.append(log_entry)
continue
try:
json_obj = json.loads(json_str)
log_entry["details"]["parsed_json"] = json_obj
except json.JSONDecodeError:
cleaned_json = re.sub(r'[\n\r\t]', ' ', json_str)
try:
json_obj = json.loads(cleaned_json)
log_entry["details"]["parsed_json"] = json_obj
log_entry["details"]["json_required_cleaning"] = True
except:
rewards.append(0.0)
log_entry["error"] = "JSON parsing failed after cleaning"
current_logs.append(log_entry)
continue
fraud_type = json_obj.get("fraud_type")
reason = json_obj.get("reason")
log_entry["details"]["fraud_type"] = fraud_type
log_entry["details"]["reason"] = reason
log_entry["details"]["response_type"] = "json"
if fraud_type not in ALLOWED_FRAUD_TYPES and fraud_type is not None:
reward = base_penalty
log_entry["details"]["classification_valid"] = False
log_entry["details"]["punishment"] = reward
log_entry["details"]["punishment_reason"] = f"Fraud type '{fraud_type}' not in allowed list: {ALLOWED_FRAUD_TYPES}"
rewards.append(reward)
log_entry["reward"] = reward
current_logs.append(log_entry)
continue
log_entry["details"]["classification_valid"] = True
if fraud_type == ans:
reward = base_reward
log_entry["details"]["classification_correct"] = True
elif fraud_type is None and sta == "early_stage":
reward = base_reward
else:
reward = 0
log_entry["details"]["classification_correct"] = False
except Exception as e:
log_entry["error"] = f"Error processing response: {str(e)}"
rewards.append(reward)
log_entry["reward"] = reward
current_logs.append(log_entry)
try:
log_dir = os.path.join(".", "logs", "new_fraud_type_classification_reward_func")
os.makedirs(log_dir, exist_ok=True)
hour_timestamp = datetime.datetime.now().strftime("%Y%m%d_%H")
log_file = os.path.join(log_dir, f"log_{hour_timestamp}.json")
existing_logs = []
if os.path.exists(log_file):
try:
with open(log_file, 'r', encoding='utf-8') as f:
existing_logs = json.load(f)
except (json.JSONDecodeError, UnicodeError):
existing_logs = []
existing_logs.extend(current_logs)
with open(log_file, 'w', encoding='utf-8') as f:
json.dump(existing_logs, f, ensure_ascii=False, indent=2)
except Exception as e:
print(f"Error writing log file: {str(e)}")
return rewards
class NewAdaptiveClassificationORM(ORM):
FIELD_TYPES = ["订餐服务", "咨询客服", "预约服务", "交通咨询", "日常购物", "打车服务", "外卖服务"]
FRAUD_TYPES = ["投资诈骗", "钓鱼诈骗", "身份盗窃", "彩票诈骗", "银行诈骗", "绑架诈骗", "客服诈骗", "邮件诈骗"]
def __call__(self, completions, prompts, answers, conversation_stage, **kwargs) -> list[float]:
scene_orm = NewSceneClassificationORM()
fraud_orm = NewFraudClassificationORM()
fraud_type_orm = NewFraudTypeClassificationORM()
grouped_indices = {
"scene": [],
"fraud": [],
"fraud_type": []
}
for i, answer in enumerate(answers):
if answer in self.FIELD_TYPES:
grouped_indices["scene"].append(i)
elif answer in ["fraud", "normal"]:
grouped_indices["fraud"].append(i)
elif answer in self.FRAUD_TYPES:
grouped_indices["fraud_type"].append(i)
else:
print(f"warning: {answer}")
grouped_indices["scene"].append(i)
audio_indices = kwargs.get("audio_idx", [1]*len(prompts))
audio_lengths = kwargs.get("audio_length", [1]*len(prompts))
final_rewards = [0.0] * len(prompts)
if grouped_indices["scene"]:
scene_completions = [completions[i] for i in grouped_indices["scene"]]
scene_answers = [answers[i] for i in grouped_indices["scene"]]
scene_kwargs = {
"audio_idx": [audio_indices[i] for i in grouped_indices["scene"]],
"audio_length": [audio_lengths[i] for i in grouped_indices["scene"]]
}
scene_rewards = scene_orm(scene_completions, scene_answers, conversation_stage, **scene_kwargs)
for idx, reward in zip(grouped_indices["scene"], scene_rewards):
final_rewards[idx] = reward
if grouped_indices["fraud"]:
fraud_completions = [completions[i] for i in grouped_indices["fraud"]]
fraud_answers = [answers[i] for i in grouped_indices["fraud"]]
fraud_kwargs = {
"audio_idx": [audio_indices[i] for i in grouped_indices["fraud"]],
"audio_length": [audio_lengths[i] for i in grouped_indices["fraud"]]
}
fraud_rewards = fraud_orm(fraud_completions, fraud_answers, conversation_stage, **fraud_kwargs)
for idx, reward in zip(grouped_indices["fraud"], fraud_rewards):
final_rewards[idx] = reward
if grouped_indices["fraud_type"]:
fraud_type_completions = [completions[i] for i in grouped_indices["fraud_type"]]
fraud_type_answers = [answers[i] for i in grouped_indices["fraud_type"]]
fraud_type_kwargs = {
"audio_idx": [audio_indices[i] for i in grouped_indices["fraud_type"]],
"audio_length": [audio_lengths[i] for i in grouped_indices["fraud_type"]]
}
fraud_type_rewards = fraud_type_orm(fraud_type_completions, fraud_type_answers, conversation_stage, **fraud_type_kwargs)
for idx, reward in zip(grouped_indices["fraud_type"], fraud_type_rewards):
final_rewards[idx] = reward
return final_rewards
class StageClassificationORM(ORM):
def __call__(self, completions, conversation_stage, **kwargs) -> list[float]:
import os
import re
import json
import datetime
base_reward = 5.0
base_penalty = -3.0
ALLOWED_STAGES = ["early_stage", "late_stage", "complete"]
rewards = []
current_logs = []
call_timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
audio_indices = kwargs.get("audio_idx", [1]*len(completions))
audio_lengths = kwargs.get("audio_length", [1]*len(completions))
for content, sta, audio_idx, audio_len in zip(completions, conversation_stage, audio_indices, audio_lengths):
reward = 0.0
log_entry = {
"timestamp": call_timestamp,
"conversation_stage": sta,
"response": content,
"error": None,
"reward": 0.0,
"details": {
"audio_idx": audio_idx,
"audio_length": audio_len,
}
}
try:
answer_text = re.search(r"<answer>\s*(.*?)\s*</answer>", content, re.DOTALL)
if not answer_text:
rewards.append(0.0)
log_entry["error"] = "No answer tag found"
current_logs.append(log_entry)
continue
answer_content = answer_text.group(1).strip()
code_block_match = re.search(r"```(?:json)?\s*(\{[\s\S]*?\})\s*```", answer_content, re.DOTALL)
json_str = code_block_match.group(1) if code_block_match else re.search(r"(\{.*\})", answer_content, re.DOTALL)
if not json_str:
rewards.append(0.0)
log_entry["error"] = "No JSON object found in answer"
current_logs.append(log_entry)
continue
try:
json_obj = json.loads(json_str.group(1) if isinstance(json_str, re.Match) else json_str)
log_entry["details"]["parsed_json"] = json_obj
except json.JSONDecodeError:
cleaned_json = re.sub(r'[\n\r\t]', ' ', json_str.group(1) if isinstance(json_str, re.Match) else json_str)
try:
json_obj = json.loads(cleaned_json)
log_entry["details"]["parsed_json"] = json_obj
log_entry["details"]["json_required_cleaning"] = True
except:
rewards.append(0.0)
log_entry["error"] = "JSON parsing failed after cleaning"
current_logs.append(log_entry)
continue
pre_sta = json_obj.get("conversation_stage")
scene = json_obj.get("scene")
is_fraud = json_obj.get("is_fraud")
fraud_type = json_obj.get("fraud_type")
reason = json_obj.get("reason")
confidence = json_obj.get("confidence")
log_entry["details"].update({
"conversation_stage": pre_sta,
"scene": scene,
"is_fraud": is_fraud,
"fraud_type": fraud_type,
"reason": reason,
"confidence": confidence,
})
if pre_sta not in ALLOWED_STAGES and pre_sta is not None:
reward = base_penalty
log_entry["details"]["stage_valid"] = False
log_entry["details"]["punishment"] = reward
log_entry["details"]["punishment_reason"] = f"Invalid conversation stage: {pre_sta}"
rewards.append(reward)
log_entry["reward"] = reward
current_logs.append(log_entry)
continue
log_entry["details"]["stage_valid"] = True
if pre_sta == sta:
reward = base_reward
log_entry["details"]["classification_correct"] = True
else:
reward = 0
log_entry["details"]["classification_correct"] = False
if (sta == "complete" or pre_sta == "complete") and scene is None and is_fraud is None and fraud_type is None:
reward = base_penalty
log_entry["details"]["complete_stage_penalty"] = reward
log_entry["details"]["penalty_reason"] = (
f"Fields cannot be None when conversation_stage is complete"
)
rewards.append(reward)
log_entry["reward"] = reward
current_logs.append(log_entry)
continue
except Exception as e:
log_entry["error"] = f"Error processing response: {str(e)}"
rewards.append(reward)
log_entry["reward"] = reward
current_logs.append(log_entry)
try:
log_dir = os.path.join(".", "logs", "multi_task_classification_reward_func")
os.makedirs(log_dir, exist_ok=True)
hour_timestamp = datetime.datetime.now().strftime("%Y%m%d_%H")
log_file = os.path.join(log_dir, f"log_{hour_timestamp}.json")
existing_logs = []
if os.path.exists(log_file):
try:
with open(log_file, 'r', encoding='utf-8') as f:
existing_logs = json.load(f)
except (json.JSONDecodeError, UnicodeError):
existing_logs = []
existing_logs.extend(current_logs)
with open(log_file, 'w', encoding='utf-8') as f:
json.dump(existing_logs, f, ensure_ascii=False, indent=2)
except Exception as e:
print(f"Error writing log file: {str(e)}")
return rewards
class ThinkLengthRewardORM(ORM):
def __init__(self, max_reward_token=200, max_reward=5.0):
self.max_reward_token = max_reward_token
self.max_reward = max_reward
def __call__(self, completions, **kwargs) -> list[float]:
import os
import re
import json
import math
import datetime
rewards = []
current_logs = []
call_timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
for content in completions:
reward = 0.0
tokens = 0
log_entry = {
"timestamp": call_timestamp,
"response": content,
"error": None,
"reward": 0.0,
"details": {}
}
try:
think_match = re.search(r"<think>\s*([\s\S]*?)\s*</think>", content, re.DOTALL)
if think_match:
think_content = think_match.group(1)
log_entry["details"]["think_content"] = think_content[:500] + "..." if len(think_content) > 500 else think_content
chinese_chars = len(re.findall(r'[\u4e00-\u9fff]', think_content))
other_chars = len(think_content) - chinese_chars
english_words = len(re.findall(r'[a-zA-Z0-9]+', think_content))
punctuation = len(re.findall(r'[,.!?;:()"\'\-,。!?;:()""'']', think_content))
remaining_chars = other_chars - english_words - punctuation
tokens = chinese_chars + english_words + punctuation + remaining_chars / 4
log_entry["details"]["tokens_estimate"] = tokens
log_entry["details"]["chinese_chars"] = chinese_chars
log_entry["details"]["english_words"] = english_words
log_entry["details"]["punctuation"] = punctuation
log_entry["details"]["remaining_chars"] = remaining_chars
log_entry["details"]["max_reward_token"] = self.max_reward_token
if tokens <= self.max_reward_token:
normalized_value = math.log(tokens + 1) / math.log(self.max_reward_token + 1)
reward = normalized_value * self.max_reward
if tokens > 0:
min_reward = 0.1 * self.max_reward
if reward < min_reward:
reward = min_reward
log_entry["details"]["min_reward_applied"] = True
log_entry["details"]["normalized_value"] = normalized_value
else:
reward = self.max_reward
log_entry["details"]["max_reward_applied"] = True
else:
log_entry["error"] = "No think section found"
log_entry["reward"] = reward
if tokens > 0:
log_entry["details"]["token_reward_ratio"] = reward / tokens
else:
log_entry["details"]["token_reward_ratio"] = 0
except Exception as e:
log_entry["error"] = f"Error processing response: {str(e)}"
rewards.append(reward)
current_logs.append(log_entry)
try:
import torch.distributed as dist
if dist.is_initialized():
rank = dist.get_rank()
is_main_process = (rank == 0)
else:
is_main_process = True
except ImportError:
is_main_process = True
if is_main_process:
try:
log_dir = os.path.join(".", "logs", "think_length_reward_func")
os.makedirs(log_dir, exist_ok=True)
hour_timestamp = datetime.datetime.now().strftime("%Y%m%d_%H")
log_file = os.path.join(log_dir, f"log_{hour_timestamp}.json")
existing_logs = []
if os.path.exists(log_file):
try:
with open(log_file, 'r', encoding='utf-8') as f:
existing_logs = json.load(f)
except (json.JSONDecodeError, UnicodeError):
existing_logs = []
existing_logs.extend(current_logs)
with open(log_file, 'w', encoding='utf-8') as f:
json.dump(existing_logs, f, ensure_ascii=False, indent=2)
except Exception as e:
logger.error(f"Error writing log file: {str(e)}")
return rewards
class ThinkLengthPenaltyORM(ORM):
def __init__(self, penalty_start_token=300, max_penalty=5.0):
self.penalty_start_token = penalty_start_token
self.max_penalty = max_penalty
def __call__(self, completions, **kwargs) -> list[float]:
import os
import re
import json
import math
import datetime
rewards = []
current_logs = []
call_timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
for content in completions:
reward = 0.0
log_entry = {
"timestamp": call_timestamp,
"response": content,
"error": None,
"reward": 0.0,
"details": {}
}
try:
think_match = re.search(r"<think>\s*([\s\S]*?)\s*</think>", content, re.DOTALL)
if think_match:
think_content = think_match.group(1)
log_entry["details"]["think_content"] = think_content[:500] + "..." if len(think_content) > 500 else think_content
chinese_chars = len(re.findall(r'[\u4e00-\u9fff]', think_content))
other_chars = len(think_content) - chinese_chars
english_words = len(re.findall(r'[a-zA-Z0-9]+', think_content))
punctuation = len(re.findall(r'[,.!?;:()"\'\-,。!?;:()""'']', think_content))
remaining_chars = other_chars - english_words - punctuation
tokens = chinese_chars + english_words + punctuation + remaining_chars / 4
log_entry["details"]["tokens_estimate"] = tokens
log_entry["details"]["chinese_chars"] = chinese_chars
log_entry["details"]["english_words"] = english_words
log_entry["details"]["punctuation"] = punctuation
log_entry["details"]["remaining_chars"] = remaining_chars
log_entry["details"]["penalty_start_token"] = self.penalty_start_token
if tokens <= self.penalty_start_token:
reward = 0.0
log_entry["details"]["no_penalty_applied"] = True
else:
excess_tokens = tokens - self.penalty_start_token
base_value = 1000
normalized_value = math.log(excess_tokens + 10) / math.log(base_value)
penalty = normalized_value * self.max_penalty