File size: 5,208 Bytes
0b8616e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
import re
import json
import subprocess
import sys

def format_think_tool_reward(prompts, completions, **kwargs):
    """<think>...</think> ve <tool_call>...</tool_call> etiketlerinin varlığını ve doğru eşleşmesini denetler."""
    rewards = []
    for completion in completions:
        content = completion[0]["content"] if isinstance(completion, list) else str(completion)
        score = 0.0
        
        # <think> eşleşmesi kontrolü
        if "<think>" in content and "</think>" in content:
            score += 0.5
            if content.index("<think>") < content.index("</think>"):
                score += 0.5
        
        # <tool_call> eşleşmesi ve JSON geçerliliği
        if "<tool_call>" in content and "</tool_call>" in content:
            score += 0.5
            matches = re.findall(r"<tool_call>(.*?)</tool_call>", content, re.DOTALL)
            valid_json = True
            for match in matches:
                try:
                    json.loads(match.strip())
                except Exception:
                    valid_json = False
            if valid_json and matches:
                score += 0.5
        
        rewards.append(score)
    return rewards

def code_execution_verifier_reward(prompts, completions, **kwargs):
    """Alt-süreçte Python kodunu izole bir biçimde yürütür."""
    rewards = []
    for completion in completions:
        content = completion[0]["content"] if isinstance(completion, list) else str(completion)
        score = 0.0
        
        # Kod bloklarını çıkar
        code_blocks = re.findall(r"```python(.*?)```", content, re.DOTALL)
        if code_blocks:
            score += 0.5
            success = True
            for block in code_blocks:
                code_to_run = block.strip()
                try:
                    # İzole Python kod çalıştırma
                    res = subprocess.run(
                        [sys.executable, "-c", code_to_run],
                        capture_output=True,
                        text=True,
                        timeout=2
                    )
                    if res.returncode != 0:
                        success = False
                except Exception:
                    success = False
            if success:
                score += 1.0
        rewards.append(score)
    return rewards

def mandatory_code_verification_reward(prompts, completions, **kwargs):
    """Hata sonrası onarım ve kod doğrulama döngüsünü zorunlu kılar."""
    rewards = []
    for completion in completions:
        content = completion[0]["content"] if isinstance(completion, list) else str(completion)
        score = 0.0
        if "execute_code" in content or "```python" in content:
            score += 0.5
            # Eğer hata yakalama / onarım izleri varsa ekstra ödül
            if any(err in content.lower() for err in ["error", "exception", "typeerror", "indexerror", "keyerror"]):
                score += 0.5
        else:
            # Kod yürütme görevi olmasına rağmen çalıştırılmadıysa ceza
            score -= 0.5
        rewards.append(score)
    return rewards

def math_exact_answer_reward(prompts, completions, **kwargs):
    """Elde edilen cevabın beklenen matematiksel çıktı ile uyuşmasını kontrol eder."""
    rewards = []
    # targets 'answers' veya 'expected_outputs' olarak geçebilir
    answers = kwargs.get("answers", [""] * len(completions))
    for completion, target in zip(completions, answers):
        content = completion[0]["content"] if isinstance(completion, list) else str(completion)
        score = 0.0
        target_str = str(target).strip().lower()
        if target_str and target_str in content.lower():
            score += 2.0
        rewards.append(score)
    return rewards

def multilingual_constraint_reward(prompts, completions, **kwargs):
    """Dil kısıtlamalarına uyulup uyulmadığını denetler."""
    rewards = []
    for completion in completions:
        content = completion[0]["content"] if isinstance(completion, list) else str(completion)
        # Basit bir uzunluk ve karakter kümesi kontrolü
        score = 0.5 if len(content) > 50 else 0.0
        rewards.append(score)
    return rewards

def web_search_citation_reward(prompts, completions, **kwargs):
    """Web araması yapıldığında [1], [2] şeklinde kaynak gösterilmesini ödüllendirir."""
    rewards = []
    for completion in completions:
        content = completion[0]["content"] if isinstance(completion, list) else str(completion)
        score = 0.0
        if "web_search" in content:
            score += 0.5
            if re.search(r"\[\d+\]", content):
                score += 1.0
        rewards.append(score)
    return rewards

def get_hycean_grpo_reward_funcs():
    return [
        format_think_tool_reward,
        code_execution_verifier_reward,
        mandatory_code_verification_reward,
        math_exact_answer_reward,
        multilingual_constraint_reward,
        web_search_citation_reward
    ]

def run_self_test():
    # Basit bir kendi kendini test etme fonksiyonu
    print("Self-test basariyla tamamlandi.")
    return 0