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
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
from pathlib import Path
from typing import Any, Callable

from jinja2 import Environment, StrictUndefined, Template


TEMPLATE_PATH = Path(__file__).parent / "chat_template.jinja"


def raise_exception(message: str) -> None:
    """
    Jinja2 şablonunun içinden Python hatası oluşturur.
    Hugging Face chat template ortamındaki raise_exception
    fonksiyonunu taklit eder.
    """
    raise ValueError(message)


def load_template() -> Template:
    """chat_template.jinja dosyasını okuyup çalıştırılabilir hâle getirir."""

    if not TEMPLATE_PATH.exists():
        raise FileNotFoundError(
            f"Template dosyası bulunamadı: {TEMPLATE_PATH.resolve()}"
        )

    template_text = TEMPLATE_PATH.read_text(encoding="utf-8")

    environment = Environment(
        undefined=StrictUndefined,
        autoescape=False,
        trim_blocks=True,
        lstrip_blocks=True,
    )

    environment.globals["raise_exception"] = raise_exception

    return environment.from_string(template_text)


def render_template(
    template: Template,
    messages: list[dict[str, Any]],
    *,
    add_generation_prompt: bool = False,
    tools: list[dict[str, Any]] | None = None,
    bos_token: str | None = None,
    eos_token: str | None = None,
) -> str:
    """Verilen mesajları chat template ile metne dönüştürür."""

    parameters: dict[str, Any] = {
        "messages": messages,
        "add_generation_prompt": add_generation_prompt,
        "bos_token": bos_token,
        "eos_token": eos_token,
    }

    if tools is not None:
        parameters["tools"] = tools

    return template.render(**parameters)


def assert_contains(output: str, expected_values: list[str]) -> None:
    """Beklenen bütün ifadelerin çıktıda bulunduğunu kontrol eder."""

    for value in expected_values:
        if value not in output:
            raise AssertionError(
                f"Beklenen ifade çıktıda bulunamadı: {value!r}"
            )


def run_success_test(
    test_name: str,
    test_function: Callable[[], str],
    expected_values: list[str],
) -> bool:
    """Başarılı olması beklenen bir testi çalıştırır."""

    print("\n" + "=" * 70)
    print(f"TEST: {test_name}")
    print("=" * 70)

    try:
        output = test_function()
        assert_contains(output, expected_values)

        print(output.strip())
        print(f"\n✅ BAŞARILI: {test_name}")
        return True

    except Exception as error:
        print(f"❌ BAŞARISIZ: {test_name}")
        print(f"Hata türü: {type(error).__name__}")
        print(f"Hata mesajı: {error}")
        return False


def run_error_test(
    test_name: str,
    test_function: Callable[[], str],
    expected_error_text: str,
) -> bool:
    """Hata vermesi beklenen bir testi çalıştırır."""

    print("\n" + "=" * 70)
    print(f"TEST: {test_name}")
    print("=" * 70)

    try:
        output = test_function()

        print(output.strip())
        print(f"\n❌ BAŞARISIZ: {test_name}")
        print("Bu testin hata vermesi gerekiyordu.")
        return False

    except Exception as error:
        if expected_error_text not in str(error):
            print(f"❌ BAŞARISIZ: {test_name}")
            print(f"Beklenmeyen hata mesajı: {error}")
            return False

        print(f"Beklenen hata yakalandı: {error}")
        print(f"✅ BAŞARILI: {test_name}")
        return True


def test_normal_conversation(template: Template) -> str:
    """System, user ve assistant rollerini test eder."""

    messages = [
        {
            "role": "system",
            "content": "Sen Türkçe cevap veren yardımcı bir asistansın.",
        },
        {
            "role": "user",
            "content": "Türkiye'nin başkenti neresidir?",
        },
        {
            "role": "assistant",
            "content": "Türkiye'nin başkenti Ankara'dır.",
        },
        {
            "role": "user",
            "content": "Peki hangi bölgede bulunur?",
        },
    ]

    return render_template(
        template,
        messages,
        add_generation_prompt=True,
    )


def test_developer_message(template: Template) -> str:
    """Developer rolünü test eder."""

    messages = [
        {
            "role": "system",
            "content": "Sen güvenilir bir yapay zekâ asistanısın.",
        },
        {
            "role": "developer",
            "content": "Cevaplarını kısa ve Türkçe olarak oluştur.",
        },
        {
            "role": "user",
            "content": "Merhaba!",
        },
    ]

    return render_template(
        template,
        messages,
        add_generation_prompt=True,
    )


def test_tool_calling(template: Template) -> str:
    """Tool tanımı, tool çağrısı ve tool sonucunu test eder."""

    tools = [
        {
            "type": "function",
            "function": {
                "name": "multiply",
                "description": "İki sayıyı çarpar.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "a": {
                            "type": "number",
                            "description": "Birinci sayı",
                        },
                        "b": {
                            "type": "number",
                            "description": "İkinci sayı",
                        },
                    },
                    "required": ["a", "b"],
                },
            },
        }
    ]

    messages = [
        {
            "role": "system",
            "content": "Gerektiğinde sana verilen araçları kullan.",
        },
        {
            "role": "user",
            "content": "12 ile 8'i çarp.",
        },
        {
            "role": "assistant",
            "content": None,
            "tool_calls": [
                {
                    "id": "call_001",
                    "type": "function",
                    "function": {
                        "name": "multiply",
                        "arguments": {
                            "a": 12,
                            "b": 8,
                        },
                    },
                }
            ],
        },
        {
            "role": "tool",
            "tool_call_id": "call_001",
            "name": "multiply",
            "content": "96",
        },
    ]

    return render_template(
        template,
        messages,
        tools=tools,
        add_generation_prompt=True,
    )


def test_multimodal_content(template: Template) -> str:
    """Metin, görsel, ses ve video içeriklerini test eder."""

    messages = [
        {
            "role": "system",
            "content": "Çok modlu içerikleri analiz edebilirsin.",
        },
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "Bu içerikleri incele:",
                },
                {
                    "type": "image",
                },
                {
                    "type": "audio",
                },
                {
                    "type": "video",
                },
                {
                    "type": "text",
                    "text": "Aralarındaki ilişkiyi açıkla.",
                },
            ],
        },
    ]

    return render_template(
        template,
        messages,
        add_generation_prompt=True,
    )


def test_custom_tokens(template: Template) -> str:
    """Tokenizer tarafından verilen BOS ve EOS tokenlarını test eder."""

    messages = [
        {
            "role": "user",
            "content": "Özel token testi yap.",
        }
    ]

    return render_template(
        template,
        messages,
        add_generation_prompt=True,
        bos_token="<s>",
        eos_token="</s>",
    )


def test_consecutive_users(template: Template) -> str:
    """Art arda iki user mesajının reddedilmesini test eder."""

    messages = [
        {
            "role": "user",
            "content": "Birinci kullanıcı mesajı.",
        },
        {
            "role": "user",
            "content": "İkinci kullanıcı mesajı.",
        },
    ]

    return render_template(template, messages)


def test_unsupported_role(template: Template) -> str:
    """Desteklenmeyen bir rolün reddedilmesini test eder."""

    messages = [
        {
            "role": "user",
            "content": "Merhaba.",
        },
        {
            "role": "moderator",
            "content": "Bu rol desteklenmemelidir.",
        },
    ]

    return render_template(template, messages)


def test_late_system_message(template: Template) -> str:
    """Konuşma başladıktan sonra system mesajını reddeder."""

    messages = [
        {
            "role": "user",
            "content": "Konuşmayı başlatıyorum.",
        },
        {
            "role": "assistant",
            "content": "Konuşma başladı.",
        },
        {
            "role": "system",
            "content": "Bu mesaj çok geç geldi.",
        },
    ]

    return render_template(template, messages)


def main() -> None:
    template = load_template()

    results = [
        run_success_test(
            "Normal sohbet",
            lambda: test_normal_conversation(template),
            [
                "<|begin_of_chat|>",
                "<|system|>",
                "<|user|>",
                "<|assistant|>",
                "<|end_message|>",
            ],
        ),
        run_success_test(
            "Developer mesajı",
            lambda: test_developer_message(template),
            [
                "<|system|>",
                "<|developer|>",
                "<|user|>",
                "<|assistant|>",
            ],
        ),
        run_success_test(
            "Tool calling",
            lambda: test_tool_calling(template),
            [
                "<|available_tools|>",
                "<|tool_call|>",
                "<|end_tool_call|>",
                "<|tool_result|>",
                "<|end_tool_result|>",
            ],
        ),
        run_success_test(
            "Çok modlu içerik",
            lambda: test_multimodal_content(template),
            [
                "<|image|>",
                "<|audio|>",
                "<|video|>",
            ],
        ),
        run_success_test(
            "Özel BOS ve EOS tokenları",
            lambda: test_custom_tokens(template),
            [
                "<s>",
                "</s>",
                "<|assistant|>",
            ],
        ),
        run_error_test(
            "Art arda iki user mesajı",
            lambda: test_consecutive_users(template),
            "İki user mesajı art arda gelemez.",
        ),
        run_error_test(
            "Desteklenmeyen rol",
            lambda: test_unsupported_role(template),
            "Desteklenmeyen rol: moderator",
        ),
        run_error_test(
            "Geç gelen system mesajı",
            lambda: test_late_system_message(template),
            "system mesajları yalnızca konuşmanın başında bulunabilir.",
        ),
    ]

    successful_tests = sum(results)
    total_tests = len(results)

    print("\n" + "#" * 70)
    print("TEST ÖZETİ")
    print("#" * 70)
    print(f"Başarılı test: {successful_tests}/{total_tests}")

    if successful_tests == total_tests:
        print("🎉 Bütün testler başarıyla tamamlandı.")
    else:
        failed_tests = total_tests - successful_tests
        print(f"⚠️ Başarısız test sayısı: {failed_tests}")
        raise SystemExit(1)


if __name__ == "__main__":
    main()