<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ogulcanakca on Medium]]></title>
        <description><![CDATA[Stories by Ogulcanakca on Medium]]></description>
        <link>https://medium.com/@ogulcanakca?source=rss-69b98f02855------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7bhypJvq3t2lxcvO</url>
            <title>Stories by Ogulcanakca on Medium</title>
            <link>https://medium.com/@ogulcanakca?source=rss-69b98f02855------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 08:44:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ogulcanakca/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Uçtan Uca Alana Özgü Kumru Base Modeli Eğitimi: Veri Hazırlığından Üretim Ortamına Optimizasyon…]]></title>
            <link>https://medium.com/@ogulcanakca/u%C3%A7tan-uca-alana-%C3%B6zg%C3%BC-kumru-base-modeli-e%C4%9Fitimi-veri-haz%C4%B1rl%C4%B1%C4%9F%C4%B1ndan-%C3%BCretim-ortam%C4%B1na-optimizasyon-dade5de0f55e?source=rss-69b98f02855------2</link>
            <guid isPermaLink="false">https://medium.com/p/dade5de0f55e</guid>
            <category><![CDATA[llm-as-a-judge]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[vllm]]></category>
            <category><![CDATA[e2e]]></category>
            <category><![CDATA[llama-cpp]]></category>
            <dc:creator><![CDATA[Ogulcanakca]]></dc:creator>
            <pubDate>Mon, 24 Nov 2025 09:59:35 GMT</pubDate>
            <atom:updated>2025-11-24T09:59:35.894Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Uçtan Uca Alana Özgü </strong>Kumru Base Modeli Eğitimi<strong>: Veri Hazırlığından Üretim Ortamına Optimizasyon Vaka Analizi</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VuoukfaAvS_Luc0-qe_5RQ.png" /></figure><p>Bu çalışmada, Enerji Piyasası Düzenleme Kurumu (EPDK) mevzuatına hakim, domain-specific bir dil modeli geliştirilmesi süreçleri uçtan uca ele alınmıştır. Proje kapsamında, yapısal olmayan ham verilerin işlenmesinden başlayarak <strong>DAPT (</strong>Domain-Adaptive Pre-Training) ve <strong>DPO (Direct Preference Optimization)</strong> yöntemleriyle modelin eğitilmesi, <strong>vLLM</strong> motoru üzerinde deployment, AWQ quantization ve model performansı üzerindeki etkilerinin ölçülmesi aşamaları gerçekleştirilmiştir.</p><p>Çalışmanın merkezinde, 2 milyar parametreli bir küçük dil modelinin (Kumru-2B), yüksek doğruluk gerektiren regülasyon alanında bir <strong>RAG (Retrieval-Augmented Generation)</strong> olarak konumlandırılıp konumlandırılamayacağı sorusu yatmaktadır.</p><h4>Bölüm 1: Veri Seti Hazırlanması</h4><ol><li><strong>Veri Toplama:</strong> EPDK mevzuatı, kurul kararları, yönetmelikler (PDF, Word, Excel) toplandı.</li><li><strong>Akıllı OCR (Qwen-VL):</strong> Standart OCR araçlarının (Tesseract) okuyamadığı tablolar ve çift sütunlu sayfalar, bir Vision-Language Model (Qwen-2.5-VL) ile metne dönüştürüldü.</li><li><strong>Sentetik Veri Üretimi (Gemini):</strong> Modelin sadece bilgiyi değil, “tercih edilen stili” de öğrenmesi için Google Gemini kullanılarak binlerce (prompt, chosen, rejected) üçlüsü içeren <strong>DPO Veri Seti</strong> oluşturuldu.</li></ol><h4>Bölüm 2: Model Eğitimi</h4><p>Türkçe yetenekleri kanıtlanmış ama alan bilgisi olmayan bir temel model, “EPDK Uzmanı”na dönüştürüldü.</p><ol><li><strong>Base Model Seçimi:</strong> vngrs-ai/Kumru-2B-Base (Türkçe SLM).</li><li><strong>DAPT:</strong> Ham corpus ile terminoloji adaptasyonu.</li><li><strong>DPO (Direct Preference Optimization):</strong> Modele “hangi cevabın daha güvenli, resmi ve doğru olduğu” (insan tercihi) öğretildi. Reward model kullanılmadan doğrudan tercih optimizasyonu yapıldı.</li></ol><h4>Bölüm 3: Quantizasyon</h4><p>Modelin farklı donanımlarda çalışabilmesi için oluşturuldu.</p><ol><li><strong>GGUF:</strong> CPU’lar için (llama.cpp).</li><li><strong>GPTQ:</strong> Orta seviye GPU’lar için.</li><li><strong>AWQ (4-bit):</strong> Production (vLLM) için hız odaklı sıkıştırma.</li></ol><h4>Bölüm 4: Deployment</h4><p>Model, sadece bir dosya olmaktan çıkıp canlı bir API servisine dönüştü.</p><ol><li><strong>Altyapı:</strong> <strong>Modal</strong> üzerinde A10G GPU kiralandı.</li><li><strong>Engine:</strong> <strong>vLLM</strong> kullanılarak “Continuous Batching” ve “PagedAttention” teknolojileriyle servis edildi.</li></ol><h4>Bölüm 5: Benchmarking ve Değerlendirme</h4><p>Projenin en kritik “karar anı” burasıydı. Hız ve Zeka teraziye kondu.</p><ul><li>Throughput, Toplam Süre (50 istek), Latency, P99 Latency</li><li>LLM-as-a-judge</li></ul><p>Bu vaka analizi, sadece bir model eğitim sürecini değil veriden servise uzanan modern bir <strong>LLMOps</strong> yaşam döngüsünü simüle etmek amacıyla yapılmıştır.</p><h4>Bölüm 1.1: EPDK Corpus Hazırlanması</h4><p>EPDK tarafından yayımlanan mevzuat, kurul kararları ve teknik tebliğler, ağırlıklı olarak taranmış PDF, Word ve Excel formatlarında, unstructured bir veri yığını halindedir. EPDK elektrik mevzuatları üzerinden hazırlanan veri kümesi, <a href="https://www.epdk.gov.tr/Detay/Icerik/23-2-3/mevzuat">diğer EPDK mevzuatlarıyla</a> kolayca birleştirilebilir, ardıl bölümlerden geçirilebilir ve veri tabanında saklanabilir. Dokümantasyonlar klasik olarak firecrawl, selenium gibi kütüphane yardımlarıyla yerele çekilmiştir.</p><p>Tesseract gibi OCR motorlarının, özellikle çok sütunlu sayfa düzenlerinde ve karmaşık tablo yapılarında metin akışını (text flow) bozduğu ve anlamsal bütünlüğü koruyamadığı gözlemlenmiştir. Mevzuat metinlerindeki madde/fıkra hiyerarşisinin korunması kritik olduğundan, standart yöntemler yetersiz kalmıştır. Bu yöntemle çıkartılan veri seti versiyon 1 olarak <a href="https://huggingface.co/datasets/ogulcanakca/epdk_corpus/tree/v1.0.0">huggingface’te</a> bulunmaktadır.</p><p>Bu sorunu aşmak için, dokümanı sadece karakter yığını olarak değil, görsel bir bütün olarak analiz edebilen <strong>Qwen-2.5-VL</strong> Vision-Language modeli bir OCR motoru olarak sisteme entegre edilmiştir. Bu yaklaşım ile:</p><ul><li>Çift sütunlu metinlerin doğru okuma sırasıyla dijitalleştirilmesi sağlanmış,</li><li>Tablo içerisindeki verilerin satır/sütun ilişkisi korunarak Markdown formatına dönüştürülmesi başarılmış,</li><li>Karakter Hata Oranı (CER — Character Error Rate) minimize edilmiştir.</li></ul><p>Elde edilen ham metinler üzerinde Regex tabanlı temizleme işlemleri uygulanarak; sayfa numaraları, üst/alt bilgiler ve tekrarlayan gürültü verileri ayıklanmış ve nihai<a href="https://huggingface.co/datasets/ogulcanakca/epdk_corpus"><strong>ogulcanakca/epdk_corpus</strong></a> veri seti oluşturulmuştur. Qwen modeli qwen_ocr_batch fonksiyonunda bu şekilde kullanılmıştır:</p><pre>def qwen_ocr_batch(images, prompt=&quot;You are an OCR engine. Transcribe the text exactly. Only output the text.&quot;):<br>    &quot;&quot;&quot;<br>    Qwen3-VL (v3 API) için chat-formatlı OCR fonksiyonu.<br>    Hem path (str) hem PIL.Image nesnesi alabilir.<br>    &quot;&quot;&quot;<br>    all_texts = []<br>    for img_in in images:<br>        if isinstance(img_in, str):<br>            from PIL import Image<br>            img = Image.open(img_in).convert(&quot;RGB&quot;)<br>        else:<br>            img = img_in<br><br>        messages = [<br>            {<br>                &quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: [<br>                    {&quot;type&quot;: &quot;image&quot;, &quot;image&quot;: img},<br>                    {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: prompt},<br>                ],<br>            }<br>        ]<br><br>        text_prompt = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)<br><br>        image_inputs = processor.image_processor(images=[img], return_tensors=&quot;pt&quot;)[&quot;pixel_values&quot;].to(model.device)<br><br>        inputs = processor(<br>            text=[text_prompt],<br>            images=[img],<br>            return_tensors=&quot;pt&quot;<br>        ).to(model.device)<br>        inputs[&quot;pixel_values&quot;] = image_inputs<br><br>        # Model tahmini<br>        with torch.inference_mode():<br>            out = model.generate(**inputs, max_new_tokens=MAX_NEW_TOKENS)<br><br>        # Çıktıyı çöz<br>        text = processor.batch_decode(out, skip_special_tokens=True)[0]<br>        all_texts.append(text.strip())<br><br>    return all_texts</pre><p>Dokümanlardan veri setinin hazırlandığı pipeline’ın tam hali <a href="https://www.kaggle.com/code/oulcanakca/epdk-dataset-qwen-vl">kaggle’da</a> yer almaktadır. Pipeline çıktısı şu şekilde bir yapı içeren veri seti oluşturmaktadır:</p><pre>{<br>  &quot;id&quot;: &quot;b3f7a6d9c49e&quot;,<br>  &quot;text&quot;: &quot;Enerji Piyasası Düzenleme Kurumundan:\nKURUL KARARI\nKarar No: 9284 Karar Tarihi: 02/04/2020\n...&quot;,<br>  &quot;kind&quot;: &quot;docx&quot;,<br>  &quot;method&quot;: &quot;python-docx&quot;<br>}</pre><h4>Bölüm 1.2: Sentetik Veri Üretimi ve DPO Hazırlığı</h4><p>Modelin eğitimi için sadece ham metin yeterli değildir. Modelin hangi soruya nasıl cevap vermesi gerektiğinin (Instruction Tuning) ve hangi cevabın “doğru/güvenli” olduğunun (Preference Learning) öğretilmesi gerekmektedir. Bu amaçla <strong>“LLM-as-a-Data-Generator”</strong> metodolojisi izlenmiştir.</p><p>Google Gemini 2.5 modelleri (Pro ve Flash) kullanılarak, EPDK corpus’u içerisindeki metinlerden otomatik olarak <strong>DPO </strong>eğitim verisi üretilmiştir. Her bir metin parçası için üçlü bir veri yapısı (Prompt, Chosen, Rejected) oluşturulması hedeflenmiştir.</p><p>Veri üretim sürecinde çıktıların tutarlılığını ve formatını garanti altına almak amacıyla <a href="https://ai.google.dev/gemini-api/docs/structured-output">Structured Output </a>desteği ve <strong>Pydantic</strong> kütüphanesi ile katı bir schema tanımlanmıştır:</p><pre>class DPO_Triplet(BaseModel):<br>    &quot;&quot;&quot;<br>    Bir DPO (Direct Preference Optimization) veri seti için<br>    prompt, chosen (tercih edilen) ve rejected (reddedilen) cevapları<br>    içeren yapı.<br>    &quot;&quot;&quot;<br>    prompt: str = Field(description=&quot;Sağlanan EPDK metnine dayalı olarak oluşturulan spesifik bir soru veya talimat.&quot;)<br>    chosen: str = Field(description=&quot;Soruya verilen ideal, doğru, eksiksiz ve YALNIZCA metne sadık kalarak oluşturulan &#39;seçilen&#39; cevap.&quot;)<br>    rejected: str = Field(description=&quot;Soruya verilen ancak kasıtlı olarak kusurlu olan &#39;reddedilen&#39; cevap. Bu cevap, kulağa makul gelebilir ama &#39;chosen&#39; cevaptan açıkça daha kötü olmalıdır (örneğin eksik bilgi, hafif yanlış tarih/sayı, ilgisiz detay ekleme vb.).&quot;)</pre><p>Seçilen Gemini modeline verilen meta prompt template bu şekildedir:</p><pre>META_PROMPT_TEMPLATE = &quot;&quot;&quot;<br>Sen bir DPO veri seti yaratıcısısın ve görevin Enerji Piyasası Düzenleme Kurumu (EPDK) metinlerini analiz etmektir.<br><br>YALNIZCA aşağıda sağlanan EPDK metnini bağlam (context) olarak kullanarak, {n} adet (prompt, chosen, rejected) üçlüsü oluştur.<br><br>1.  **prompt:** Metin hakkında spesifik bir soru veya talimat oluştur.<br>2.  **chosen:** Bu &#39;prompt&#39; için metindeki bilgilere dayanarak mükemmel, doğru ve eksiksiz bir cevap oluştur.<br>3.  **rejected:** Bu &#39;prompt&#39; için makul görünen ama &#39;chosen&#39; cevaptan açıkça daha kötü (örneğin; bilgiyi eksik veren, metindeki bir sayıyı/tarihi hafifçe yanlış yazan veya konuyu biraz saptıran) bir cevap oluştur.<br><br>Kesinlikle metnin dışından bilgi ekleme. Cevabın JSON formatında olmalı.<br><br>--- BAĞLAM (CONTEXT) METNİ ---<br>{epdk_metni}<br>--- BİTTİ ---<br>&quot;&quot;&quot;</pre><p>Sentetik veri kümesi hazırlanmasının yer aldığı pipeline <a href="https://www.kaggle.com/code/oulcanakca/gemini-dpo-dataset-multi">kaggle’da</a> yer almaktadır. Bu süreç sonucunda, insan etiketleme maliyetine katlanılmadan, modelin “tercih edilen davranışı” öğrenmesini sağlayacak <strong>24.500+</strong> satırlık sentetik bir veri seti <a href="https://huggingface.co/datasets/ogulcanakca/epdk_dpo">ogulcanakca/epdk_dpo</a>elde edilmiştir. Pipeline çıktısı şu şekilde bir yapı içeren veri seti oluşturmaktadır:</p><pre>{<br>&quot;original_id&quot;: &quot;e7480801c5b2&quot;, <br>&quot;sub_id&quot;: &quot;e7480801c5b2_8&quot;, <br>&quot;prompt&quot;: &quot;EPİAŞ&#39;ın elektrik piyasasında tanımları nelerdir?&quot;, <br>&quot;chosen&quot;: &quot;EPİAŞ, Enerji Piyasaları İşletme Anonim Şirketini; Kurul, Enerji Piyasası Düzenleme Kurulunu; Piyasa İşletim Gelir Tavanı ise EPİAŞ’ın bir tarife yılında toplayacağı gelirin üst sınırını ifade eder (MADDE 4/1).&quot;, <br>&quot;rejected&quot;: &quot;EPİAŞ, Enerji Piyasaları İşletme Anonim Şirketidir ve Piyasa İşletim Gelir Tavanı, EPİAŞ&#39;ın sadece bir yıllık gelir üst sınırıdır.&quot;<br>}</pre><h4><strong>Bölüm 2: Model Eğitimi ve Hizalama Stratejileri</strong></h4><p>Veri setinin hazırlanmasının ardından, projenin ikinci fazı olan model eğitimi sürecine geçilmiştir. Bu aşamada temel hedef, general purpose bir Türkçe dil modelinin, EPDK terminolojisine hakim, mevzuat sorularına resmi bir dille yanıt verebilen ve halüsinasyon oranı minimize edilmiş bir “Instruct” modeline dönüştürülmesidir.</p><p>Eğitim mimarisi olarak, donanım kısıtları ve inference hızı gözetilerek <strong>2 milyar parametreli</strong> <a href="https://huggingface.co/vngrs-ai/Kumru-2B-Base">vngrs-ai/Kumru-2B-Base</a> modeli temel alınmıştır. Eğitim süreci iki bölümde kurgulanmıştır: <strong>DAPT </strong>ve <strong>DPO.</strong></p><h4><strong>Bölüm 2.1: </strong>Alan Bilgisi Yüklemesi (DAPT)</h4><p>General purpose dil modellerinin, enerji piyasası gibi yüksek teknik yoğunluğa sahip alanlarda doğrudan kullanılması, terminoloji eksikliği ve bağlam kopukluğu risklerini barındırmaktadır. Bu nedenle, alanın literatürüne ve jargonuna hakim olması (Domain Adaptation) hedeflenmiştir.</p><p>Bu aşamada, hazırlanan <a href="https://huggingface.co/datasets/ogulcanakca/epdk_corpus"><strong>ogulcanakca/epdk_corpus</strong></a> veri setindeki ham mevzuat metinleri, kurul kararları ve teknik tebliğler kullanılarak modele <strong>Continued Pre-training</strong> uygulanmıştır. Unsupervised Learning prensibiyle yürütülen bu süreçte, modelin <strong>&quot;Next Token Prediction&quot; </strong>görevi üzerinden EPDK mevzuatının mantıksal akışını, kanun yapım tekniğini ve sektörel kavramları (Örn: YEKDEM, PİGT, TORETOSAF) içselleştirmesi sağlanmıştır.</p><p>Donanım verimliliğini korumak adına bu aşamada <strong>QLoRA</strong> tekniği tercih edilmiştir. Bu eğitimdeki config’ler bu şekildedir:</p><pre>bnb_config = BitsAndBytesConfig(<br>    load_in_4bit=True,<br>    bnb_4bit_quant_type=&quot;nf4&quot;,<br>    bnb_4bit_compute_dtype=torch.bfloat16<br>)<br><br>peft_config = LoraConfig(<br>    r=16,                           <br>    lora_alpha=32,                  <br>    lora_dropout=0.05,              <br>    bias=&quot;none&quot;,                    <br>    task_type=&quot;CAUSAL_LM&quot;,<br>    target_modules=[<br>        &quot;q_proj&quot;,<br>        &quot;k_proj&quot;,<br>        &quot;v_proj&quot;,<br>        &quot;o_proj&quot;,<br>        &quot;gate_proj&quot;,<br>        &quot;up_proj&quot;,<br>        &quot;down_proj&quot;,<br>    ],<br>)<br><br>sft_config_args = SFTConfig(<br>    max_length=4096,<br>    packing=True,<br>    dataset_text_field=&quot;text&quot;,  <br>    output_dir=output_dir,<br>    num_train_epochs=3,<br>    per_device_train_batch_size=1,<br>    gradient_accumulation_steps=16, <br>    gradient_checkpointing=True,    <br>    bf16=True,                      <br>    optim=&quot;paged_adamw_8bit&quot;,       <br>    learning_rate=1e-5,<br>    lr_scheduler_type=&quot;cosine&quot;,<br>    warmup_ratio=0.03,<br>    <br>    logging_strategy=&quot;steps&quot;,<br>    logging_steps=10,<br>    save_strategy=&quot;epoch&quot;,<br>    save_total_limit=2,<br>    <br>    push_to_hub=True,<br>    hub_model_id=hub_model_id,<br>    hub_strategy=&quot;end&quot;,<br>    report_to=&quot;wandb&quot;,     <br>    run_name=new_model_name<br>)</pre><p>QLoRA ile 2,392,095,744 parametresi bulunan Kumru 2B Base modelinin 16,957,440 kadar parametresi eğitilmiştir. Yüzdesel olarak bu %0.7089&#39;a denk gelmektedir. Bu eğitimin detayları <a href="https://www.kaggle.com/code/oulcanakca/kumru-epdk-corpus-dapt">kaggle’da </a>yer almaktadır. Çeşitli metriklerinin yer aldığı WandB raporu da <a href="https://api.wandb.ai/links/ogulcanakca-none/3g7ewqgi">burada </a>yer almaktadır.</p><h4>Bölüm 2.2: DPO ile Tercih Optimizasyonu ve Hizalama</h4><p>DAPT eğitimi almış bir model, terminoloji açısından hakim olsa da, yanıtın doğruluğu ve üslubu konusunda her zaman istenilen standartta olmayabilir. Geleneksel RLHF (Reinforcement Learning from Human Feedback) yöntemlerinin aksine, ayrı bir reward model gerektirmeyen ve daha stabil bir eğitim sunan <strong>DPO </strong>yöntemi tercih edilmiştir.</p><p>Önceki bölümde Gemini kullanılarak üretilen sentetik veri seti (<a href="https://huggingface.co/datasets/ogulcanakca/epdk_dpo">ogulcanakca/epdk_dpo</a>), bu aşamada devreye alınmıştır. Model, &quot;Chosen&quot; (Doğru/Resmi) ve &quot;Rejected&quot; (Hatalı/Eksik) yanıtlar arasındaki farkı (log-probability farkları üzerinden) öğrenmeye zorlanmıştır.</p><p>Eğitim stabilitesini artırmak ve overfitting’i önlemek adına <strong>IPO (Identity Preference Optimization)</strong> loss fonksiyonu kullanılmış ve kritik hiperparametreler aşağıdaki gibi yapılandırılmıştır:</p><pre>bnb_config = BitsAndBytesConfig(<br>    load_in_4bit=True,<br>    bnb_4bit_quant_type=&quot;nf4&quot;,<br>    bnb_4bit_compute_dtype=torch.bfloat16<br>)<br><br>peft_config = LoraConfig(<br>    r=16,<br>    lora_alpha=32,<br>    lora_dropout=0.05,<br>    bias=&quot;none&quot;,<br>    task_type=&quot;CAUSAL_LM&quot;,<br>    target_modules=[&quot;q_proj&quot;, &quot;k_proj&quot;, &quot;v_proj&quot;, &quot;o_proj&quot;, &quot;gate_proj&quot;, &quot;up_proj&quot;, &quot;down_proj&quot;]<br>)<br><br>training_args = DPOConfig(<br>    output_dir=f&quot;./results/{run_name}&quot;,<br>    per_device_train_batch_size=4,<br>    gradient_accumulation_steps=2,<br>    learning_rate=5e-5,<br>    num_train_epochs=1,<br>    lr_scheduler_type=&quot;cosine&quot;,<br>    optim=&quot;paged_adamw_8bit&quot;,<br>    <br>    logging_steps=25,<br>    save_steps=25,<br>    save_total_limit=2,<br>    <br>    report_to=&quot;wandb&quot;,<br>    run_name=run_name,<br>    <br>    fp16=not torch.cuda.is_bf16_supported(), <br>    bf16=torch.cuda.is_bf16_supported(),     <br>    <br>    beta=0.1, <br>    max_length=2048,<br>    max_prompt_length=1024,<br>    <br>    gradient_checkpointing=True,<br>    precompute_ref_log_probs=False,<br>    loss_type=&quot;ipo&quot;,<br>    <br>    eval_strategy=&quot;steps&quot;,   <br>    eval_steps=25,             <br>    generate_during_eval=True,<br>    remove_unused_columns=False,<br>    per_device_eval_batch_size=8,<br>)</pre><p>Bu config’lerle gerçekleştirilen eğitim sonucunda, modelin validation setindeki “doğru cevabı seçme” (accuracy) oranının <strong>%94</strong> seviyelerine ulaştığı ve margin değerlerinin istikrarlı bir şekilde artma trendinde olduğu gözlemlenmiştir. Bu durum, modelin sadece ezberlemediğini, tercih edilen yanıt kalıbını genelleştirebildiğini göstermektedir. Bu eğitimin detayları <a href="https://www.kaggle.com/code/oulcanakca/kumru-epdk-dpo">kaggle’da</a> yer almaktadır. Çeşitli metriklerinin yer aldığı WandB raporu da <a href="https://api.wandb.ai/links/ogulcanakca-none/z06caml6">burada </a>yer almaktadır.</p><h4>Bölüm 3: Model Birleştirme, Optimizasyon</h4><p>Eğitim süreçlerinin tamamlanmasının ardından, modelin farklı donanım kısıtları altında çalışabilir hale getirilmesi hedeflenmiştir. Bu bölümde ayrı ayrı eğitilen adaptör katmanlarının merge edilmesi, modelin farklı formatlarda quantize edilmesi ve ölçeklenebilir bir inference server’ı üzerinde servis edilmesi süreçleri gerçekleştirilmiştir.</p><h4>Bölüm 3.1: Adaptör Birleştirme</h4><p>Önceki bölümlerde, DAPT (Alan Bilgisi) ve DPO (Davranışsal Hizalama) aşamaları için ayrı LoRA (Low-Rank Adaptation) adaptörleri eğitilmiştir. Inference sırasında ek latency maliyetinden kaçınmak ve model yönetimini basitleştirmek amacıyla, bu adaptör katmanları <a href="https://huggingface.co/vngrs-ai/Kumru-2B-Base">vngrs-ai/Kumru-2B-Base</a> temel modeli ile kalıcı olarak birleştirilmiştir.</p><pre>from peft import AutoPeftModelForCausalLM<br>from transformers import AutoTokenizer<br><br>base = &quot;vngrs-ai/Kumru-2B&quot;<br>sft_adapter = &quot;./epdk_sft_adapter&quot;<br>merged_sft = &quot;./kumru_epdk_sft_merged&quot;<br>dpo_adapter = &quot;./epdk_dpo_adapter&quot;<br>final_merged = &quot;./kumru_epdk_final_merged&quot;<br><br>model = AutoPeftModelForCausalLM.from_pretrained(sft_adapter, device_map=&quot;auto&quot;)<br>model = model.merge_and_unload()<br>model.save_pretrained(merged_sft, safe_serialization=True)<br><br>tok = AutoTokenizer.from_pretrained(base, use_fast=True)<br>tok.save_pretrained(merged_sft)<br><br>model = AutoPeftModelForCausalLM.from_pretrained(dpo_adapter, device_map=&quot;auto&quot;)<br>model = model.merge_and_unload()<br>model.save_pretrained(final_merged, safe_serialization=True)</pre><p>Bu işlem sonucunda, harici bir adaptör yüklemesine ihtiyaç duymayan, EPDK mevzuatına hakim ve talimat takip yeteneği kazanmış tek bir nihai model weights elde edilmiştir. Nihai model <a href="https://huggingface.co/ogulcanakca/Kumru-2B-EPDK-Instruct">huggingface’te</a>, örnek prompt ve çıktısı aşağıda yer almaktadır.</p><pre>{<br>  &quot;prompt&quot;: &quot;2007 yılına ait Türkiye Ortalama Elektrik Toptan Satış Fiyatının (TORETOSAF) değeri nedir?&quot;,<br>  &quot;Instruct Model&quot;: &quot;TORETOSAF, 2013 yılı için, 12 aylık TÜFE ile TEFE arasındaki farktır. 2013 yılı için % 10,11’dir.&quot;<br>}</pre><h4>Bölüm 3.2: Quantization Stratejileri</h4><p>Modelin sadece yüksek kapasiteli sunucularda değil, kısıtlı kaynağa sahip edge device’larda veya tüketici sınıfı GPU’larda da çalışabilmesi için bir “Model Ailesi” yaklaşımı benimsenmiştir. Nihai model, kullanım senaryosuna göre üç farklı formatta optimize edilmiştir:</p><ol><li><strong>GGUF (</strong>Generic GPT Unified Format) <strong>(CPU Inference):</strong> Modelin, GPU erişimi olmayan ortamlarda (örn. yerel bilgisayarlar) llama.cpp kütüphanesi ile çalıştırılabilmesi için GGUF formatına dönüştürülmüştür.</li><li><strong>GPTQ </strong>(Generative Pre-trained Transformer Quantization) <strong>(GPU Inference):</strong> Standart PyTorch ve Hugging Face entegrasyonları ile uyumlu, orta seviye GPU’larda (T4/L4) verimli çalışması için 4-bit GPTQ sıkıştırması uygulanmıştır.</li><li><strong>AWQ (Production Inference):</strong> Canlı sistemde kullanılacak vLLM motoru ile en yüksek uyumluluğu ve memory bandwidth efficiency sağladığı için, activation-aware 4-bit AWQ sıkıştırması, ana dağıtım formatı olarak belirlenmiş, benchmark ve değerlendirme yapılmıştır.</li></ol><h4>Bölüm 3.2.1: GGUF</h4><p>Yüksek VRAM kapasiteli GPU’lara erişimin olmadığı lokal geliştirme ortamları ve uç cihazlar (örneğin Apple Silicon veya standart laptoplar) için model <strong>GGUF</strong> formatına dönüştürülmüştür. llama.cpp ekosistemi ile tam uyumlu olan bu format sayesinde, model ağırlıkları 4-bit (Q4_K_S, Q4_K_M), 5-bit (Q5_K_M), 6-bit (Q6_K) ve 8-bit (Q8_0) seviyelerine indirilerek RAM kullanımı minimize edilmiş ve modelin standart bir CPU üzerinde makul hızlarda çalıştırılması mümkün kılınmıştır. Ek olarak 16-bit versiyonu da <a href="https://huggingface.co/ogulcanakca/Kumru-2B-EPDK-Instruct-GGUF">huggingface’te</a> yer almaktadır.</p><p>Ubuntu WSL’de sırasıyla aşağıdaki komutlar çalıştırılmıştır:</p><pre>gh repo clone ggml-org/llama.cpp<br><br>cd ~/llama.cpp<br>git pull<br>pip3 install -r requirements.txt<br>make clean<br>make -j$(nproc)<br><br>cd ~/llama.cpp<br>python3 convert-hf-to-gguf.py ./kumru2b_epdk_merged --outfile kumru2b_epdk_merged_f16.gguf<br><br>./quantize kumru2b_epdk_merged_f16.gguf kumru2b_epdk_merged_q4_k_s.gguf Q4_K_S<br><br>./quantize kumru2b_epdk_merged_f16.gguf kumru2b_epdk_merged_q4_k_m.gguf Q4_K_M<br><br>./quantize kumru2b_epdk_merged_f16.gguf kumru2b_epdk_merged_q5_k_m.gguf Q5_K_M<br><br>./quantize kumru2b_epdk_merged_f16.gguf kumru2b_epdk_merged_q6_k.gguf Q6_K<br><br>./quantize kumru2b_epdk_merged_f16.gguf kumru2b_epdk_merged_q8_0.gguf Q8_0</pre><h4>Bölüm 3.2.2: GPTQ</h4><p>Orta seviye sunucu GPU’ları (örneğin NVIDIA T4 veya L4) ve standart Hugging Face transformers kütüphanesi ile entegrasyon gerektiren senaryolar için <strong>GPTQ</strong> yöntemi uygulanmıştır. Kalibrasyon veri seti olarak c4 kullanılarak gerçekleştirilen bu işlemde, ağırlık matrisleri row-wise sıkıştırılmıştır. GPTQ formatındaki model <a href="https://huggingface.co/ogulcanakca/Kumru-2B-EPDK-Instruct-GPTQ-4bit">huggingface’te</a>, config ve kod aşağıda yer almaktadır.</p><pre>from transformers import AutoModelForCausalLM, AutoTokenizer, GPTQConfig<br><br>model_name = &quot;ogulcanakca/Kumru-2B-EPDK-Instruct&quot;<br>save_dir = &quot;kumru-2b-epdk-gptq-4bit&quot;<br><br>tokenizer = AutoTokenizer.from_pretrained(model_name)<br><br>quant_config = GPTQConfig(<br>    bits=4,<br>    group_size=128,<br>    dataset=&quot;c4&quot;,        <br>    tokenizer=tokenizer,<br>)<br><br>model = AutoModelForCausalLM.from_pretrained(<br>    model_name,<br>    device_map=&quot;auto&quot;,<br>    quantization_config=quant_config,<br>)<br><br>model.save_pretrained(save_dir)<br>tokenizer.save_pretrained(save_dir)</pre><h4>Bölüm 3.2.3: AWQ</h4><p>Production ortamında kullanılacak vLLM motoru ile en yüksek uyumluluğu ve throughput sağlaması nedeniyle, <strong>AWQ</strong> ana dağıtım formatı olarak değerlendirilmiştir. AWQ, tüm ağırlıkları eşit şekilde sıkıştırmak yerine, modelin aktivasyonlarında önemli rol oynayan ağırlıkları koruyarak hassasiyet kaybını minimize etmeyi amaçlayan bir tekniktir. Bu projede, üretim ortamındaki memory bandwidth efficiency’i maksimize etmek amacıyla model, autoawq kütüphanesi kullanılarak 4-bit hassasiyete indirgenmiştir. AWQ formatındaki model <a href="https://huggingface.co/ogulcanakca/Kumru-2B-EPDK-Instruct-AWQ-4bit">huggingface’te</a>, config ve kod aşağıda yer almaktadır.</p><pre>from awq import AutoAWQForCausalLM<br>from transformers import AutoTokenizer<br><br>model_name = &quot;ogulcanakca/Kumru-2B-EPDK-Instruct&quot;<br>save_dir = &quot;kumru-2b-epdk-awq&quot;<br><br>model = AutoAWQForCausalLM.from_pretrained(<br>    model_name,<br>    safetensors=True,<br>)<br><br>tokenizer = AutoTokenizer.from_pretrained(model_name)<br><br>quant_config = {<br>    &quot;zero_point&quot;: True,      <br>    &quot;q_group_size&quot;: 128,    <br>    &quot;w_bit&quot;: 4,             <br>}<br><br>model.quantize(tokenizer, quant_config)<br><br>model.save_quantized(save_dir)<br>tokenizer.save_pretrained(save_dir)</pre><h4>Bölüm 4: Üretim Ortamı Mimarisi: vLLM ve Modal Entegrasyonu</h4><p>Modelin son kullanıcılara ölçeklenebilir, yüksek performanslı bir API olarak sunulması aşamasında, serverless GPU altyapısı sağlayan <strong>Modal</strong> platformu ve Inference Engine olarak <strong>vLLM</strong> tercih edilmiştir. Bu mimari seçiminde, kaynak verimliliği ve anlık talep artışlarına (burst traffic) yanıt verebilme yeteneği belirleyici olmuştur.</p><h4>Bölüm 4.1: Mikro-Servis Altyapısı ve Donanım Seçimi</h4><p>Production ortamı için maliyet/performans dengesi gözetilerek <strong>NVIDIA A10G (24GB VRAM)</strong> GPU üzerinde bir mikro-servis mimarisi kurgulanmıştır. Modelin OpenAI-compatible bir API arayüzü ile sunulması sağlanarak, mevcut RAG ve Chatbot sistemlerine entegrasyonu standartlaştırılmıştır.</p><h4>Bölüm 4.2: vLLM ve Config’leri</h4><p>Modelin serve edilmesi sırasında, vLLM motorunun sunduğu “PagedAttention” ve “Continuous Batching” teknolojilerinden maksimum düzeyde faydalanmak için aşağıdaki spesifik config’ler uygulanmıştır:</p><ul><li><strong>Cold-Start Optimizasyonu:</strong> Sunucusuz mimarilerde kritik bir metrik olan “ilk açılış süresini” minimize etmek amacıyla, vLLM’in CUDA grafiklerini derleme süreci --enforce-eager parametresi ile atlanmış; böylece konteynerin ayağa kalkma süresi (boot time) düşürülmüştür.</li><li><strong>Context Window Yönetimi:</strong> EPDK mevzuat metinlerinin uzunluğu ve RAG senaryoları dikkate alınarak, --max-model-len parametresi <strong>4096 token</strong> ile sınırlandırılmıştır. Bu kısıtlama, GPU belleğinde KV Cache için ayrılan alanın optimize edilmesini sağlamıştır.</li><li><strong>Hassasiyet ve Format:</strong> Model ağırlıkları, donanım uyumluluğu ve çıkarım hızı dengesi gözetilerek <strong>FP16 (Half Precision)</strong> formatında yüklenmiştir.</li></ul><pre>cmd = [<br>    &quot;vllm&quot;, &quot;serve&quot;, MODEL_NAME,<br>    &quot;--host&quot;, &quot;0.0.0.0&quot;,<br>    &quot;--port&quot;, &quot;8000&quot;,<br>    &quot;--dtype&quot;, &quot;half&quot;,             # FP16 hassasiyet<br>    &quot;--max-model-len&quot;, &quot;4096&quot;,     # Bağlam sınırı<br>    &quot;--tensor-parallel-size&quot;, &quot;1&quot;, # Tek A10G GPU kullanımı<br>    &quot;--enforce-eager&quot;,             # Hızlı boot (Eager Mode)<br>    &quot;--trust-remote-code&quot;<br>]</pre><ul><li><strong>Tensor Paralelliği:</strong> Modelin boyutu ve GPU mimarisinin kapasitesi dikkate alınarak, vLLM’in --tensor-parallel-size parametresi 1 olarak bırakılmıştır. Bu değer, A10G GPU’nun tek başına 2B parametreli bir modeli rahatlıkla çalıştırabilmesi nedeniyle tercih edilmiştir. Yük artışı veya daha büyük modellerde bu parametre yatay ölçekleme için kolayca artırılabilir yapıdadır.</li><li><strong>Cache Yönetimi ve Disk Persistence:</strong> Model yükleme sürelerini hızlandırmak için vllm_cache ve Hugging Face hf_cache dizinleri kalıcı Modal Volume&#39;lar ile eşlenmiştir. Böylece tekrarlanan cold start modelin ve tokenizer&#39;ın yeniden indirilme gereksinimi ortadan kaldırılmıştır. KV Cache ise GPU belleğinde runtime sırasında PagedAttention mekanizması ile dinamik olarak yönetilmektedir.</li><li><strong>Uvicorn Sunucu Ayarları:</strong> vLLM servisinin OpenAI API ile uyumlu bir HTTP endpoint sunması için, altyapı Uvicorn üzerinde çalışacak şekilde ayarlanmıştır. --uvicorn-log-level info değeri hem performansı hem de hata analizini optimize etmesi nedeniyle seçilmiştir.</li><li><strong>Concurrency Optimizasyonu:</strong> Modal fonksiyonuna eklenen @modal.concurrent(max_inputs=32) yapısı, vLLM’in Continuous Batching kabiliyetinden tam faydalanabilmesi için tasarlanmıştır. Böylece aynı anda onlarca istek tek bir büyük batch altında işlenerek GPU verimliliği artırılmıştır.</li><li><strong>Model İsmi ve API Uyumlaştırma:</strong> vLLM tarafında model sunumu sırasında --served-model-name parametresi kullanılarak OpenAI formatında erişilebilen bir model adı atanmıştır (kumru-2b-epdk). Bu sayede istemci tarafında OpenAI SDK ile tamamen şeffaf ve sorunsuz kullanım mümkün hale gelmiştir.</li></ul><p>Bu kısmın yer aldığı kod aşağıda bulunmaktadır.</p><pre># kumru_vllm_inference.py<br><br>import modal<br><br>MODEL_NAME = &quot;ogulcanakca/Kumru-2B-EPDK-Instruct-AWQ-4bit&quot;<br>SERVED_MODEL_NAME = &quot;kumru-2b-epdk&quot;<br><br>GPU_TYPE = &quot;A10G&quot;<br>N_GPU = 1<br>FAST_BOOT = True<br>VLLM_PORT = 8000<br>MIN = 60<br><br>vllm_image = (<br>    modal.Image.from_registry(<br>        &quot;nvidia/cuda:12.8.0-devel-ubuntu22.04&quot;,<br>        add_python=&quot;3.12&quot;,<br>    )<br>    .entrypoint([])<br>    .uv_pip_install(<br>        &quot;vllm==0.11.0&quot;,<br>        &quot;huggingface-hub==0.36.0&quot;,<br>        &quot;flashinfer-python==0.3.1&quot;,<br>    )<br>    .env({&quot;HF_XET_HIGH_PERFORMANCE&quot;: &quot;1&quot;})<br>)<br><br>hf_cache = modal.Volume.from_name(&quot;kumru-hf-cache&quot;, create_if_missing=True)<br>vllm_cache = modal.Volume.from_name(&quot;kumru-vllm-cache&quot;, create_if_missing=True)<br><br>app = modal.App(&quot;kumru-vllm-inference&quot;)<br><br>@app.function(<br>    image=vllm_image,<br>    gpu=GPU_TYPE,<br>    timeout=10 * MIN,<br>    scaledown_window=15 * MIN,<br>    volumes={<br>        &quot;/root/.cache/huggingface&quot;: hf_cache,<br>        &quot;/root/.cache/vllm&quot;: vllm_cache,<br>    },<br>)<br>@modal.concurrent(max_inputs=32)<br>@modal.web_server(port=VLLM_PORT, startup_timeout=10 * MIN)<br>def serve():<br>    import subprocess<br><br>    cmd = [<br>        &quot;vllm&quot;,<br>        &quot;serve&quot;,<br>        MODEL_NAME,<br>        &quot;--host&quot;, &quot;0.0.0.0&quot;,<br>        &quot;--port&quot;, str(VLLM_PORT),<br>        &quot;--quantization&quot;, &quot;awq&quot;,<br>        &quot;--max-model-len&quot;, &quot;4096&quot;,<br>        &quot;--tensor-parallel-size&quot;, str(N_GPU),<br>        &quot;--served-model-name&quot;, SERVED_MODEL_NAME,<br>        &quot;--trust-remote-code&quot;,<br>        &quot;--uvicorn-log-level&quot;, &quot;info&quot;,<br>    ]<br><br>    if FAST_BOOT:<br>        cmd.append(&quot;--enforce-eager&quot;)<br>    else:<br>        cmd.append(&quot;--no-enforce-eager&quot;)<br><br>    print(&quot;Çalıştırılan komut:&quot;)<br>    print(&quot; &quot;.join(cmd))<br><br>    subprocess.Popen(cmd)<br><br><br>@app.local_entrypoint()<br>def main():<br>    import time, requests<br><br>    url = serve.web_url<br>    print(f&quot;Sunucu URL&#39;i: {url}&quot;)<br><br>    for _ in range(25):<br>        try:<br>            if requests.get(f&quot;{url}/health&quot;).status_code == 200:<br>                print(&quot;✅ vLLM ayakta!&quot;)<br>                break<br>        except:<br>            time.sleep(2)<br><br>    print(f&quot;\nOpenAI endpoint: {url}/v1/chat/completions&quot;)<br>    print(f&quot;Model adı: {SERVED_MODEL_NAME}&quot;)</pre><pre>modal deploy kumru_vllm_inference.py</pre><p>şeklinde çalıştırılan bu kodu test etmek amaçlı aşağıdaki client hazırlanmıştır.</p><pre># test_client.py<br><br>import asyncio<br>from openai import AsyncOpenAI<br>from transformers import AutoTokenizer<br><br>BASE_URL = &quot;https://ogulcanakca--kumru-vllm-inference-serve.modal.run&quot;<br>MODEL_NAME = &quot;ogulcanakca/Kumru-2B-EPDK-Instruct&quot;<br><br>tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)<br><br>client = AsyncOpenAI(<br>    base_url=f&quot;{BASE_URL}/v1&quot;,<br>    api_key=&quot;dummy&quot;<br>)<br><br>def build_injected_message(query, index):<br>    messages = [<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;Elektrik Piyasası Denetleme Kurulu (EPDK) mevzuatları konusunda uzmansın.&quot;},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: f&quot;{query} (Test #{index})&quot;}<br>    ]<br><br>    template_text = tokenizer.apply_chat_template(<br>        messages,<br>        tokenize=False,<br>        add_generation_prompt=True<br>    )<br><br>    return [<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: template_text}<br>    ]<br><br><br>async def ask(index):<br>    try:<br>        injected_messages = build_injected_message(<br>            &quot;EPDK&#39;nın kuruluş amacı nedir?&quot;,<br>            index<br>        )<br><br>        response = await client.chat.completions.create(<br>        model=&quot;kumru-2b-epdk&quot;,<br>        messages=injected_messages,<br>        max_tokens=200,<br>        temperature=0.1,<br>        top_p=0.85,<br>        frequency_penalty=1.2,<br>        presence_penalty=0.8<br>    )<br><br><br>        answer = response.choices[0].message.content<br>        return f&quot;\n# {index}\n{answer}\n&quot;<br><br>    except Exception as e:<br>        return f&quot;[ERROR] #{index} -&gt; {e}&quot;<br><br><br>async def main():<br>    N = 20<br>    print(f&quot;{N} paralel request gönderiliyor...\n&quot;)<br><br>    tasks = [ask(i) for i in range(1, N+1)]<br>    results = await asyncio.gather(*tasks)<br><br>    print(&quot;\n=== SONUÇLAR ===&quot;)<br>    for r in results:<br>        print(r)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(main())</pre><pre>python test_client.py</pre><p>ile çıktılarımızı aynı anda alabildik. Loglardaki önemli çıktılar:</p><ul><li>Model yükleme süresi: ~1.9 s</li><li>GPU KV cache boyutu: 523,616 token</li><li>Prefix cache hit rate: 57.8%</li><li>İstek duration: ~122–124 s, execution ~2–4 s</li><li>Prompt throughput: 97.6 tokens/s</li><li>Generation throughput: 321.3 tokens/s</li><li>GPU KV cache kullanımı: 0% (yükleme sırasında)</li></ul><p>Sunucu normal şekilde çalışıyor ve chat endpointleri aktif. Deploy edilen app</p><pre>modal app stop kumru-vllm-inference</pre><p>ile durdurulabilir. Bu mimari ile model, talep olmadığı anlarda uyku moduna geçerek (scale-to-zero) maliyet avantajı sağlarken, gelen isteklere milisaniyeler içinde yanıt verebilecek bir hazır bulunuşluk seviyesine getirilmiştir.</p><h4>Bölüm 5: Benchmarking ve Evaluation</h4><p>Projenin son aşamasında, canlıya alınan modelin üretim ortamındaki davranışları nicel verilerle analiz edilmiştir. Bu analizde, <strong>hız </strong>ve d<strong>oğruluk olarak </strong>iki kritik başarı faktörü ele alınmıştır:</p><p>Değerlendirme sürecinde, endüstri standardı kabul edilen <strong>“Oracle RAG” (Gold Context)</strong> metodolojisi izlenmiştir. Böylece modelin retrieval hatalarından bağımsız olarak, sadece kendisine sunulan doğru bilgiyi işleme ve reasoning kapasitesi ölçülmüştür. Testler, <strong>FP16 (Orijinal Ağırlıklar)</strong> ve <strong>AWQ (4-bit quantized) </strong>modelleri üzerinde, eş zamanlı 50 kullanıcı yükü altında gerçekleştirilmiştir.</p><h4>Bölüm 5.1: Hesaplama Performansı: Throughput ve Latency Analizi</h4><p>Sunucu tarafında yapılan stres testlerinde, vLLM engine’inin farklı model formatlarındaki kuyruk yönetimi ve token üretim hızları ölçülmüştür.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwXEbsQCwlQNkajjzPEcQA.png" /></figure><p>Veriler incelendiğinde, FP16 modelinin yüksek VRAM kullanımı nedeniyle istekleri sıraya aldığı (queuing) ve P99 gecikmesinin 100 saniyeye ulaştığı görülmüştür. Buna karşın AWQ modeli, bellek bant genişliği verimliliği sayesinde darboğazı aşmış ve saniyede 850 token üretim hızına ulaşarak hesaplama performansı açısından üstünlük sağlamıştır.</p><h4>Bölüm 5.2: Oracle RAG</h4><p>Hız artışının modelin zekası üzerindeki etkisini ölçmek amacıyla, modelin dışarıdan verilen doğru context’i kullanarak soruyu cevaplama yeteneği RAG başarısını ölçmek amacıyla test edilmiştir. Bu testte, <strong>“LLM-as-a-Judge”</strong> yaklaşımı kullanılmış ve Google Gemini 2.5 Flash modeli, üretilen cevapları doğruluk ve tutarlılık açısından 1 ile 5 arasında puanlamıştır. Structured output desteğiyle hazırlanan değerlendirme fonksiyonu aşağıda yer almaktadır.</p><pre>    <br>def get_judge_evaluation(question, reference, student_answer):<br>    &quot;&quot;&quot;Gemini Structured Output kullanarak değerlendirme yapar.&quot;&quot;&quot;<br>    <br>    judge_prompt = f&quot;&quot;&quot;<br>    Aşağıdaki soruya verilen cevabı, referans cevaba (doğru bilgiye) göre değerlendir.<br><br>    SORU: {question}<br>    <br>    REFERANS CEVAP: {reference}<br>    <br>    ÖĞRENCİ MODELİN CEVABI: {student_answer}<br><br>    GÖREV:<br>    Öğrenci modelin cevabını objektif olarak değerlendir.<br>    - Puanlama (1-5): 5 (Tam uyumlu), 3 (Kısmen doğru/eksik), 1 (Yanlış/Alakasız).<br>    - Halüsinasyon olup olmadığına dikkat et.<br>    &quot;&quot;&quot;<br>    <br>    response = judge_client.models.generate_content(<br>        model=&quot;gemini-2.5-flash-lite&quot;,<br>        contents=judge_prompt,<br>        config=types.GenerateContentConfig(<br>            response_mime_type=&quot;application/json&quot;,<br>            response_schema=JudgeResult, <br>            temperature=0.1<br>        )<br>    )<br>    return response.parsed </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*764v81ZR7SXJ6NHR-QWBaw.png" /></figure><p>Test sonuçları, 2 milyar parametreli küçük modellerde (SLM) 4-bit sıkıştırmanın, modelin dilbilgisel yapısını ve muhakeme yeteneğini belli bir oranda bozduğunu göstermiştir. AWQ modeli, yüksek hıza rağmen, verilen bağlamı anlamlı bir cevaba dönüştürmekte başarısız sayılabilir ki bu beklenen bir şey aynı zamanda. Kumru-2B-EPDK-Instruct, yüksek hassasiyet gerektiren enerji hukuku alanında nasıl bir performans sergilediği uçtan uca analiz edilmiştir. Veri mühendisliğinden model sıkıştırmaya kadar uzanan bu süreç, özellikle Production ortamı kararlarında veriye dayalı yaklaşımın önemini ortaya koymaktadır.</p><h4>Sonuç ve Sonraki Adımlar</h4><p>Bu çalışmanın kapsamı, sadece modelin eğitimi ve optimizasyonu ile sınırlı kalmamıştır. Geliştirilen model, mevzuat dokümanları üzerinde işleyen Advanced <strong>RAG </strong>hattına entegre edilerek gerçek dünya senaryolarındaki doküman-sorgu performansı doğrulanmıştır. RAG tarafında reranking ve indexing stratejileri de kullanılmıştır. Vektör veri tabanı olarak Milvus’un cloud versiyonu ziliz.cloud kullanılmış olup embedding modeli gemini-embedding-001 kullanılmıştır.</p><p>Buna ek olarak, canlı sistemin güvenliğini ve mevzuat uyumluluğunu garanti altına almak adına mimariye <strong>NVIDIA NeMo Guardrails</strong> katmanı dahil edilmiştir. Bu katman ile modelin uygunluk denetimi, içerik filtrelemesi ve domain-boundary kontrol altına alınmıştır. User prompt’u ve sistem çıktıları Comet Opik ile trace edilmiştir.</p><p><em>Makalenin teknik odağını ve akıcılığını korumak amacıyla detayları ayrı bir teknik incelemenin konusu olabilecek bu entegrasyonlar; projenin veri hazırlığından güvenli dağıtıma uzanan uçtan uca (end-to-end) ve profesyonel niteliğini tamamlayan final yapıtaşları olarak kurgulanmıştır. Ayrıca çalışmanın teknik mimarisi ve uygulama süreçleri, LLM Engineer’s Handbook: Master the Art of Engineering Large Language Models kitabında sunulan mühendislik prensipleri temel alınarak yapılandırılmıştır. Kitabın incelenmesi sürecinde oluşturulan teknik notlar ve metodolojiler, bu projede uçtan uca bir LLM lifecycle olarak pratiğe dökülmüştür.</em></p><p>Geliştirilen pipeline’ın endüstriyel standartlara uyumu ve sürdürülebilirliği için <strong>data versioning</strong> mekanizmalarının entegre edilmesiyle zaman içindeki <strong>data drift</strong>’in tespit edilmesi ve veri hattı tutarlılığının korunması ele alınabilir. Ayrıca, veri işleme, eğitim ve dağıtım süreçlerinin izlenebilirliği ve tekrarlanabilirliği için <strong>ZenML gibi MLOps orkestrasyon araçlarının</strong> yapıya dahil edilmesi sistemin olgunluğunu artıracaktır. Performans açısından, mikroservis iletişiminde HTTP yerine daha düşük gecikme sunan <strong>gRPC</strong>’ye geçiş yapılması ve sık tekrarlanan mevzuat sorguları için <strong>Semantic Caching</strong> veya <strong>GPTCache</strong> kullanılarak GPU yükü ile yanıt sürelerinin azaltılması ölçeklenebilirlik için önerilen başlıca iyileştirmelerdir.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dade5de0f55e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agentic Sistemlerin Temelleri ve Uygulamaları]]></title>
            <link>https://medium.com/@ogulcanakca/agentic-sistemlerin-temelleri-ve-uygulamalar%C4%B1-5f5b5691f626?source=rss-69b98f02855------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f5b5691f626</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[literature]]></category>
            <category><![CDATA[ai-framework]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Ogulcanakca]]></dc:creator>
            <pubDate>Mon, 24 Nov 2025 09:57:14 GMT</pubDate>
            <atom:updated>2025-11-24T09:57:14.913Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q6o31EHoyhak7Zmq4HkAtw.png" /></figure><p>En basit tanımıyla agentic yapı, bir yapay zeka modelinin sadece pasif bir şekilde komutlara cevap veren bir araç olmaktan çıkıp, belirli bir hedefe ulaşmak için kendi kendine düşünen, plan yapan, araçlar kullanan ve otonom bir şekilde hareket eden bir <strong>agent</strong> gibi davranmasını sağlayan mimaridir.</p><p>Bu sistemler genellikle döngüsel bir mantıkla çalışır. Sistemin “beyni” olarak GPT-4, Claude 3 veya Gemini gibi Büyük Dil Modelleri (LLM) görev yapar. Bu beyin, gelen bilgileri anlar, durumu değerlendirir ve bir sonraki adımın ne olması gerektiğine karar verir.</p><p>Karmaşık bir hedef verildiğinde, bunu “Önce A’yı yapmalıyım, sonra B’den gelen sonuçla C’yi denemeliyim” şeklinde alt görevlere böler. Elbette bu sürecin sağlıklı işlemesi için agent’ın ne yaptığını unutmaması gerekir. İşte burada <strong>Conversation Buffer</strong> veya <strong>Episodic Memory</strong> gibi hafıza yapıları devreye girer. En önemlisi, bu agent’lar çevreleriyle etkileşime geçebilir. Dosya oluşturabilir, kod çalıştırabilir veya API çağrıları yapabilirler.</p><p>Peki ama bir dil modelini, bu kadar yetenekli bir yapıya dönüştüren temel taşlar nelerdir? Her şey, modelin düşünme şeklini değiştirmekle başladı.</p><h3>1. Chain-of-Thought (CoT)</h3><p>Bir agent’ın en temel ihtiyacı, akıl yürütebilmektir. Google Research ekibinin öncülüğünde hayatımıza giren <strong>Chain-of-Thought (CoT)</strong>, modele karmaşık bir problemi adım adım düşünerek çözmeyi öğretti. Tıpkı bir insanın matematik problemini çözerken işlem adımlarını tek tek yazması gibi, bu yöntem modelin bir iç sese sahip olmasını sağladı.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*US_lPXa5TQo9NZ8KaJ3NTw.png" /></figure><p>Figure 2&#39;de görülebileceği üzere, PaLM modeli CoT kullandığında, o dönem için state-of-the-art bir başarı oranına ulaşmıştı. Ancak, sadece düşünmek yetmez, agent dediğimiz yapının dış dünyayla etkileşime girmesi gerekir. Çünkü CoT, sadece modelin içsel bilgisine dayanır ve bu bilgi güncel değilse halüsinasyon riski doğar.</p><h3>2. ReAct</h3><p>İşte bu noktada <strong>ReAct</strong> paradigması devreye girdi. ReAct, CoT ile kazandığımız düşünme yeteneğini, eyleme geçme ile birleştirdi.</p><p>Artık döngümüz şu şekildedir: <strong>Thought </strong>⟶ <strong>Action </strong>⟶<strong> Observation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*VjRopVr_oyZmDCPNMFuLAA.png" /></figure><p>Örneğin, “Apple Remote” ile ilgili bir soruda (bkz. Figure 3, 1d), model önce neyi araması gerektiğini düşünür (Thought), aramayı yapar (Action), gelen sonucu gözlemler (Observation) ve bu yeni bilgiyle tekrar düşünerek bir sonraki adıma karar verir. Plansız eylemin (1c) veya sadece düşünmenin (1b) aksine, bu kombinasyonun başarısı tablolarda açıkça görülmektedir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*nSu3_me0X39nKI5zrv3MIA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*now9Ay3QnZI_w5zm9e1Vqw.png" /></figure><h3>3. Araç Kullanımını Öğrenmek: Toolformer</h3><p>Bir modelin ne zaman araç kullanacağına nasıl karar verdiğini merak ediyorsanız, Meta AI ekibinin <strong>Toolformer</strong> çalışmasına bakmalıyız.</p><p>Toolformer’ın mantığı oldukça zariftir: “Bir API çağrısı, metnin geri kalanını tahmin etmeyi kolaylaştırıyorsa faydalıdır”. Model, kendi kendine milyonlarca potansiyel API çağrısı üretir, bunları dener ve sadece işe yarayanları öğrenme verisine katar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*XZ4TYLzSrZdPK3VMKYicVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*SAvuGYw99m9V9LT2Abo6wQ.png" /></figure><p>Sonuç mu? 6.7 milyar parametreli Toolformer, doğru aracı kullanarak, kendisinden 25 kat büyük olan 175 milyar parametreli GPT-3&#39;ü birçok alanda geride bırakmayı başarmıştır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*XxWj1bim69DkVRWe5OlAvg.png" /></figure><h3>4. Planning ve Decision Making</h3><p>Agentic sistemlerin beyni sadece bir sonraki kelimeyi tahmin etmekle kalmaz, uzun vadeli planlar yapar. Literatürde <strong>Tree of Thoughts</strong> gibi yapılar, agent’ın tek bir yoldan gitmek yerine, farklı çözüm yollarını aynı anda değerlendirip en mantıklısını seçmesine olanak tanır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*2UxVXU6UEeapTWTMmB0N_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*im2ke0d4DGgn-27AZ8-GHQ.png" /></figure><p>Bunun en çarpıcı örneği <strong>Voyager</strong> projesidir. Minecraft ortamında çalışan bu agent, insan müdahalesi olmadan dünyayı keşfeder, yeni beceriler edinir ve bu becerileri <strong>Skill Library</strong> yapısına ekleyerek <strong>Lifelong Learning</strong> gerçekleştirir.</p><p><a href="https://voyager.minedojo.org/assets/videos/gallery/house.mp4">https://voyager.minedojo.org/assets/videos/gallery/house.mp4</a></p><h3>5. Multi-Agent Sistemler</h3><p>Tek bir agent yeteneklidir, peki ya birden fazla agent iş birliği yaparsa? <strong>AutoGPT</strong> ve <strong>CAMEL</strong> gibi yapılar tam olarak buna odaklanır.</p><p>Örneğin CAMEL mimarisinde, “bir borsa botu geliştir” gibi genel bir görev verildiğinde, bir “Python Programcısı” agent’ı ve bir “Borsa Yatırımcısı” agent’ı oluşturulur. Bu iki agent, tıpkı insanlar gibi karşılıklı konuşarak görevi tamamlar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*sxYYJplaphJvHhYEr1xjdQ.png" /></figure><p>Ancak bu çoklu yapılar, <strong>Safety</strong> ve <strong>Alignment</strong> problemlerini de beraberinde getirir. Örneğin, “kötü niyetli” bir senaryoda (The Bad Mind), agent’ların dünyayı ele geçirmek için nasıl detaylı ve tehlikeli planlar yapabildiğini simülasyonlarda görebiliyoruz. Tek başına zararsız görünen agent’lar, etkileşim halindeyken beklenmedik riskler oluşturabilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SHrDFvcbS5pAUBraSN6hXQ.png" /></figure><h3>6. Frameworkler</h3><p>Bugün bu karmaşık sistemleri sıfırdan yazmak zorunda değiliz. Geliştirici ekosisteminde öne çıkan güçlü frameworkler var:</p><ul><li><strong>LangChain:</strong> En popüler kütüphanelerden biri. Farklı LLM’ler, memory türleri ve hazır agent şablonları sunar.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Tlne-ndBFIGb6rf3oGCpg.png" /></figure><ul><li><strong>Haystack:</strong> Özellikle production odaklı, ölçeklenebilir pipeline’lar kurmak için idealdir.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xMIGBdstTVmD1cxKZ0-2SQ.png" /></figure><ul><li><strong>LlamaIndex:</strong> Veri odaklıdır. Özellikle RAG uygulamaları için verilerinizi LLM’lerin anlayacağı şekilde indekslemede çok güçlüdür.</li><li><strong>AutoGen:</strong> Microsoft tarafından geliştirilen, Multi-agent conversation ve collaboration için tasarlanmış bir frameworktür.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VkIelvzz5fdLSZRi9aImQw.png" /></figure><h3>7. Kullanım Alanları</h3><p>Artık agent’ları sadece chatbot olarak görmüyoruz.</p><ul><li><strong>Corporate RAG:</strong> Şirket içi tüm bilgi birikimine hakim, çalışanlara asistanlık yapan uzmanlar.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*SA04N8PXqxOq7d4xjm5BOw.png" /></figure><ul><li><strong>Researcher Agents:</strong> Google’ın <strong>AI co-scientist</strong> projesi gibi, bilimsel literatürü tarayıp hipotez üreten sistemler.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*NFLJJp-AXBz7yTGZ7VaOFQ.png" /></figure><ul><li><strong>Developer Agents:</strong> <strong>Devin</strong> gibi, uçtan uca yazılım geliştirip hata ayıklayabilen “AI yazılım mühendisleri”.</li></ul><p>Elbette Hallucination, Latency, Cost ve Scalability gibi zorluklarımız hala mevcut. Ayrıca değerlendirme metriği eksikliği de önemli bir problem. Ancak gelecek, <strong>Plan &amp; Act</strong> mimarileriyle daha uzun vadeli düşünebilen ve <strong>A-MEM</strong> gibi sistemlerle öğrendiklerini unutmayan, hafızasını evrimleştiren agent’lara doğru gidiyor.</p><p>Sonuç olarak, tam otonomiye giden yolda <strong>Human-in-the-loop</strong> stratejisiyle, insanın yaratıcılığını ve etik muhakemesini, AI’ın hızıyla birleşen hibrit bir geleceğe doğru ilerliyoruz.</p><p><em>Bu yazı, Agentic Sistemler üzerine yaptığım sunum ve literatür taraması notlarımdan derlenmiştir.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f5b5691f626" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Türkçe Image Captioning: BLIP ile Sıfır Noktasından Bir Başlangıca]]></title>
            <link>https://medium.com/@ogulcanakca/t%C3%BCrk%C3%A7e-image-captioning-blip-ile-s%C4%B1f%C4%B1r-noktas%C4%B1ndan-bir-ba%C5%9Flang%C4%B1ca-2c7da2d7acd2?source=rss-69b98f02855------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c7da2d7acd2</guid>
            <category><![CDATA[blip]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[image-captioning]]></category>
            <category><![CDATA[vlm]]></category>
            <dc:creator><![CDATA[Ogulcanakca]]></dc:creator>
            <pubDate>Wed, 04 Jun 2025 13:01:15 GMT</pubDate>
            <atom:updated>2025-06-04T13:01:15.298Z</atom:updated>
            <content:encoded><![CDATA[<p>Görsel dünyayı kelimelerle buluşturmak, yapay zekanın en heyecan verici alanlarından biri. Özellikle Türkçe gibi, kaynakların İngilizceye kıyasla daha sınırlı olduğu dillerde bu tür projeler geliştirmek hem zorlayıcı hem de bir o kadar değerli. Bu yazıda, Kaggle P100 GPU gibi mütevazı bir donanımla Salesforce/blip-image-captioning-base modelini kullanarak ituperceptron/image-captioning-turkish veri kümesi üzerinde Türkçe görüntü altyazılama yeteneği kazandırma serüvenimizi ve bu sürecin nasıl &quot;orta karar ama umut vadeden bir başlangıç noktası&quot; oluşturduğunu ele alacağız.</p><p><strong>Projemizin Amacı:</strong></p><p>Temel hedefimiz, verilen bir görsele bakarak onu Türkçe, açıklayıcı ve anlamlı cümlelerle tarif edebilen bir model geliştirmekti. Bu, özellikle erişilebilirlik, içerik yönetimi ve daha birçok alanda Türkçe konuşan kullanıcılar için büyük bir potansiyel taşıyor.</p><p><strong>Kullanılan Araçlar:</strong></p><ul><li><strong>Model:</strong> Salesforce/blip-image-captioning-base</li><li><strong>Veri Kümesi:</strong> ituperceptron/image-captioning-turkish (&quot;long_captions&quot; yapılandırmasından bir alt küme)</li><li><strong>Platform:</strong> Kaggle P100 GPU</li><li><strong>Kütüphaneler:</strong> Hugging Face Transformers, Datasets, Evaluate, PyTorch, Accelerate</li></ul><h3>Adım 1: Mevcut Yeteneklerin Keşfi — Zero-Shot Denemesi</h3><p>Herhangi bir ince ayar yapmadan önce, seçtiğimiz BLIP modelinin “kutudan çıktığı haliyle” Türkçe altyazılama konusunda ne yapabildiğini görmek istedik. Bu, “zero-shot” çıkarım olarak bilinir. blip-turkish-image-captioning-0shot.ipynb adlı notebook&#39;umuzda bu denemeyi gerçekleştirdik.</p><p><strong>Zero-Shot Çıkarım Kodu (Özet):</strong></p><pre># Model ve İşlemci Yükleme<br>model_id = &quot;Salesforce/blip-image-captioning-base&quot;<br>processor = BlipProcessor.from_pretrained(model_id)<br>model = BlipForConditionalGeneration.from_pretrained(model_id, torch_dtype=torch.float16).to(device)<br>model.eval()<br><br># Veri Kümesinden Örnekler Alma<br>dataset_name = &quot;ituperceptron/image-captioning-turkish&quot;<br>split_to_load = &quot;long_captions&quot;<br>num_samples_for_zero_shot = 5<br>ds_iterable = load_dataset(dataset_name, split=split_to_load, streaming=True)<br>zero_shot_samples = list(ds_iterable.take(num_samples_for_zero_shot))<br><br># Prompt ve Çıkarım<br>text_prompt_turkish = &quot;türkçe altyazı:&quot;<br>for i, sample in enumerate(zero_shot_samples):<br>    image = sample[&#39;image&#39;].convert(&quot;RGB&quot;)<br>    inputs = processor(images=image, text=text_prompt_turkish, return_tensors=&quot;pt&quot;).to(device, torch.float16) #<br>    with torch.no_grad():<br>        generated_ids = model.generate(**inputs, max_new_tokens=70) <br>    generated_caption = processor.decode(generated_ids[0], skip_special_tokens=True) <br>    # ... (çıktıları yazdırma) ...</pre><p><strong>Zero-Shot Sonuçları ve Kalitatif Analiz:</strong></p><p>blip-turkish-image-captioning-0shot (1).ipynb notebook&#39;undaki denemelerimiz şu tür sonuçlar verdi:</p><p><strong>Örnek 1 (Plaj Görüntüsü):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*v_zM2BMsyVgVHT3fgaJHIg.png" /><figcaption>Plaj görüntüsü</figcaption></figure><ul><li>Gerçek Altyazı (Detaylı Türkçe): <em>Görüntü, dağınık bulutların olduğu açık mavi bir gökyüzü altında canlı bir plaj manzarasını tasvir ediyor…</em></li><li>Modelin Ürettiği (Zero-Shot): turkce altyazı :i beach resort the beach</li></ul><p><strong>Örnek 2 (Cami İçi):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*oy5nCwq0sTtN4pTwsseRXw.png" /><figcaption>Cami içi görüntüsü</figcaption></figure><ul><li>Gerçek Altyazı (Detaylı Türkçe): <em>Görüntü, karmaşık mimari detayları ve canlı renkleriyle karakterize edilen büyük bir caminin iç mekanını tasvir ediyor…</em></li><li>Modelin Ürettiği (Zero-Shot): turkce altyazı :jaja mosque, the largest mosque in the world</li></ul><p><strong>Örnek 3 (Neuschwanstein Kalesi):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*yt_0Ti8QmeBTy-sxIyIt0A.png" /><figcaption><em>Neuschwanstein Kalesi</em></figcaption></figure><ul><li>Gerçek Altyazı (Detaylı Türkçe): <em>Görüntü, Almanya’nın Bavyera Alpleri’nde yer alan ünlü bir simge olan Neuschwanstein Kalesi’ni gözler önüne seriyor…</em></li><li>Modelin Ürettiği (Zero-Shot): turkce altyazı : castle in the winter</li></ul><p>Model, görsellerin ana temasını (plaj, cami, kale) genel olarak İngilizce kelimelerle yakalayabiliyor. “türkçe altyazı :” prompt’unu çıktıya dahil etse de, devamını İngilizce getiriyor. Bu, Salesforce/blip-image-captioning-base modelinin öncelikle İngilizce veriyle eğitildiğini ve zero-shot olarak akıcı, detaylı Türkçe altyazılar üretmekte zorlandığını gösteriyor. Üretilen metinler, &quot;long_captions&quot; formatındaki zengin ve uzun açıklamalardan oldukça uzak. Bu durum, Türkçe görüntü altyazılama görevine özel bir ince ayarın (fine-tuning) ne kadar kritik olduğunu açıkça ortaya koyuyor.</p><h3>Adım 2: Modelin Eğitimi — BLIP ile Türkçe Altyazılamaya İnce Ayar</h3><p>Zero-shot denemelerinden aldığımız dersle, BLIP modelini ituperceptron/image-captioning-turkish veri kümesinin long_captions split&#39;inden seçtiğimiz yaklaşık 60.000 örnek üzerinde (P100 GPU&#39;nun kısıtlamalarını göz önünde bulundurarak) ince ayar yapmaya başladık. Bu süreç, &quot;blip-turkish-image-captioning-fine-tune.ipynb&quot; adlı notebook&#39;umuzda detaylandırıldı.</p><p><strong>İnce Ayar Sürecinden Önemli Noktalar (Planlanan ve Uygulananlar):</strong></p><ul><li><strong>Veri Hazırlığı:</strong> long_captions split&#39;inden 60.000 (veya bellek durumuna göre ayarlanmış) örnek seçildi. Görüntüler ve Türkçe altyazılar (text sütunu) BlipProcessor kullanılarak modele uygun formata getirildi. TEXT_MAX_LENGTH gibi bir sabit ile altyazı uzunlukları sınırlandırıldı.</li><li><strong>Model Yükleme:</strong> Salesforce/blip-image-captioning-base modeli torch.float16 ile yüklendi. QLoRA gibi yöntemlere bu daha küçük model için başlangıçta gerek duyulmadı.</li><li><strong>TrainingArguments:</strong></li><li>per_device_eval_batch_size=1 (OOM hatalarını önlemek için kritik).</li><li>fp16=True (P100&#39;de performans ve bellek için).</li><li>generation_max_length (veya model.config.text_config.max_length) değerlendirme sırasında üretilecek altyazıların uzunluğunu kontrol etmek için ayarlandı (örn: 70 token).</li><li>Öğrenme oranı (~2e-5), batch boyutu (örn: cihaz başına 4, gradyan biriktirme ile efektif 16) gibi hiperparametreler P100&#39;e göre optimize edildi.</li><li><strong>Metrikler:</strong> Eğitim sırasında ve sonunda model performansını ölçmek için sacrebleu (BLEU için), ROUGE ve METEOR metriklerini kullanan bir compute_metrics fonksiyonu tanımlandı.</li><li><strong>Eğitim:</strong> Trainer sınıfı kullanılarak model birkaç epoch boyunca eğitildi. PYTORCH_CUDA_ALLOC_CONF ortam değişkeni ve gc.collect(), torch.cuda.empty_cache() gibi bellek yönetimi teknikleri uygulandı.</li></ul><h3>Adım 3: İnce Ayar Sonrası Performans ve Kalitatif Analiz</h3><p>İnce ayar sürecinin ardından, modelin Türkçe altyazılama yeteneğinde önemli bir gelişme gözlemlemeyi bekliyoruz.</p><p><strong>Kalitatif Karşılaştırma (Zero-Shot vs. Fine-Tuned):</strong></p><p>Aynı görseller için ince ayar yapılmış modelin üreteceği (beklenen) altyazılar:</p><p><strong>Örnek 1 (Plaj Görüntüsü):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*v_zM2BMsyVgVHT3fgaJHIg.png" /><figcaption>Plaj görüntüsü</figcaption></figure><ul><li>Gerçek Altyazı: <em>Görüntü, dağınık bulutların olduğu açık mavi bir gökyüzü altında canlı bir plaj manzarasını tasvir ediyor…</em></li><li>Zero-Shot (BLIP): turkce altyazı :i beach resort the beach</li><li><strong>İnce Ayar Sonrası:</strong> “insanların bir plaj manzarasını tasvir ediyor ;r iskelet, suyun uzerinde uzanan canlı bir plaj manzarasını tasvir ediyor. on planda, bi”</li></ul><p><strong>Örnek 2 (Cami İçi):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*oy5nCwq0sTtN4pTwsseRXw.png" /><figcaption>Cami içi görüntüsü</figcaption></figure><ul><li>Gerçek Altyazı: <em>Görüntü, karmaşık mimari detayları ve canlı renkleriyle karakterize edilen büyük bir caminin iç mekanını tasvir ediyor…</em></li><li>Zero-Shot (BLIP): turkce altyazı :jaja mosque, the largest mosque in the world</li><li><strong>İnce Ayar Sonrası:</strong> “kemerli pencereler ve karmasık mimari detaylarla suslennmis buyuk, suslu bir yapıyı tasvir ediyor. yapı, karmasık desenlerle suslenmis buyuk”</li></ul><p><strong>Örnek 3 (Neuschwanstein Kalesi):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*yt_0Ti8QmeBTy-sxIyIt0A.png" /><figcaption><em>Neuschwanstein Kalesi</em></figcaption></figure><ul><li>Gerçek Altyazı: <em>Görüntü, Almanya’nın Bavyera Alpleri’nde yer alan ünlü bir simge olan Neuschwanstein Kalesi’ni gözler önüne seriyor…</em></li><li>Zero-Shot (BLIP): turkce altyazı : castle in the winter</li><li><strong>İnce Ayar Sonrası:</strong> “muhtemelen bir kale veya kalesi olan cok katlı birık katlıntı yakalıyor. yapı, cok sayıda kemerli pencereye sahip belirgin bir kuleye sahip”</li></ul><p>Salesforce/blip-image-captioning-base modelinin, ituperceptron/image-captioning-turkish veri kümesinin long_captions split&#39;inden alınan 20.000 örneklik bir alt küme ile P100 GPU üzerinde eğitilmesi sonucunda elde edilen test metrikleri şu şekildedir:</p><ul><li><strong>SacreBLEU:</strong> 0.1129</li><li><strong>ROUGE-L:</strong> 0.2852</li><li><strong>ROUGE-1:</strong> 0.3486</li><li><strong>METEOR:</strong> 0.2978</li></ul><p><strong>Bu Metrikler Ne Anlama Geliyor?</strong></p><p>Bu metrikler, modelimizin Türkçe altyazılama görevini belirli bir seviyede öğrendiğini gösteriyor:</p><ul><li><strong>SacreBLEU (%11.29):</strong> Bu metrik, üretilen altyazılardaki n-gram’ların (ardışık kelime dizileri) referans altyazılardaki n-gram’larla ne kadar örtüştüğünü ölçer. %11 civarında bir skor, modelin bazı doğru kelime sıralamaları ve ifadeler ürettiğini, ancak insan tarafından yazılmış referanslarla tam uyum ve akıcılık konusunda daha fazla iyileştirmeye açık olduğunu gösterir. Görüntü altyazılama görevlerinde bu metrik için 10–30 aralığı, veri kümesi ve model karmaşıklığına bağlı olarak sıkça görülebilir.</li><li><strong>ROUGE-1 (%34.86) ve ROUGE-L (%28.52):</strong> ROUGE metrikleri, üretilen ve referans altyazılar arasındaki kelime (ROUGE-1) ve en uzun ortak alt dizi (ROUGE-L) eşleşmelerine bakar. %28–35 aralığındaki bu skorlar, modelin konuyla ilgili anahtar kelimeleri yakalayabildiğini ve cümle yapısında kısmi bir benzerlik oluşturabildiğini işaret eder. Bu, özellikle zero-shot denemelerindeki (çoğunlukla İngilizce ve çok kısa çıktılar) sonuçlara kıyasla önemli bir ilerlemedir.</li><li><strong>METEOR (%29.78):</strong> METEOR, sadece kelime eşleşmelerine değil, aynı zamanda kelime köklerine, eş anlamlılara (İngilizce için daha güçlüdür) ve genel hizalamaya da bakar. %29 civarında bir skor, üretilen altyazıların anlamsal olarak referanslara oldukça yakın olduğunu ve insan değerlendirmeleriyle genellikle daha iyi korelasyon gösterdiğini düşündürür. Bu, metrikler arasında en umut verici olanlardan biridir.</li></ul><p><strong>Genel Yorum:</strong> Elde edilen bu metrikler, özellikle P100 gibi kısıtlı bir donanım ve 10.000 gibi nispeten küçük bir veri alt kümesi ile çalışıldığı düşünüldüğünde, modelin Türkçe altyazı üretme görevini <strong>öğrenmeye başladığını ve temel bir yetkinlik kazandığını</strong> göstermektedir. Zero-shot denemelerindeki neredeyse tamamen alakasız veya İngilizce çıktılara kıyasla, model artık Türkçe ve konuyla daha ilintili altyazılar üretebilmektedir.</p><p>Elbette, bu skorlar “son teknoloji” (state-of-the-art) seviyesinde olmayabilir ve daha fazla veri, daha büyük modeller veya daha uzun eğitim süreleriyle önemli ölçüde artırılabilir. Ancak bu sonuçlar, projenin amacına ulaştığını ve Türkçe görüntü altyazılama için <strong>değerli bir “orta başlangıç noktası”</strong> oluşturduğunu teyit etmektedir. Bu metrikler, modelin potansiyelini ve daha ileri çalışmalar için iyi bir temel sunduğunu gösterir. Kalitatif analiz (üretilen altyazı örneklerinin incelenmesi) ile bu sayısal değerler desteklendiğinde, modelin güçlü ve zayıf yanları daha net anlaşılacaktır.</p><h3>Sonuç: “Orta Karar Ama Değerli Bir Başlangıç Noktası”</h3><p>Bu proje, kısıtlı donanım kaynaklarıyla bile Türkçe görüntü altyazılama için bir BLIP modelinin nasıl eğitilebileceğini ve sıfırdan (zero-shot) duruma kıyasla ne kadar iyileştirilebileceğini göstermiştir. Elde edilen model, mükemmel olmasa da, Türkçe VLM alanında daha ileri çalışmalar için <strong>sağlam bir “orta başlangıç noktası”</strong> sunmaktadır.</p><p>Gelecekteki adımlar şunları içerebilir:</p><ul><li>Daha fazla veri ile eğitim (tüm long_captions split&#39;i veya ek Türkçe veri kaynakları).</li><li>Daha büyük model mimarileri (donanım izin verirse).</li><li>Hiperparametre optimizasyonunun derinleştirilmesi.</li><li>Farklı prompt stratejilerinin denenmesi.</li><li>Ve tabii ki, eğer model daha büyük ve çıkarım hızı kritikse, vLLM gibi kütüphanelerle çıkarım optimizasyonunun tekrar değerlendirilmesi.</li><li><strong><em>Notebook 1:</em></strong><em> </em><a href="https://www.kaggle.com/code/oulcanakca/blip-turkish-image-captioning-0shot"><em>blip-turkish-image-captioning-0shot noteobook’u</em></a></li><li><strong><em>Notebook 2:</em></strong><em> </em><a href="https://www.kaggle.com/code/oulcanakca/blip-turkish-image-captioning-fine-tune"><em>blip-turkish-image-captioning-fine-tune notebook’u</em></a></li><li><strong><em>Notebook 3:</em></strong><em> </em><a href="https://www.kaggle.com/code/oulcanakca/blip-turkish-image-captioning-test"><em>blip-turkish-image-captioning-test notebook’u</em></a></li><li><strong><em>Notebook 4:</em></strong><em> </em><a href="https://www.kaggle.com/code/oulcanakca/blip-turkish-image-captioning-inference"><em>blip-turkish-image-captioning-inference notebook’u</em></a></li><li><strong><em>Model:</em></strong><em> </em><a href="https://huggingface.co/ogulcanakca/blip-itu-turkish-captions-finetuned"><em>ogulcanakca/blip-itu-turkish-captions-finetuned</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c7da2d7acd2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Raw Regulations to a Domain-Smart LLM: A Practical Journey in Fine-tuning Llama 3 on Turkish…]]></title>
            <link>https://medium.com/@ogulcanakca/from-raw-regulations-to-a-domain-smart-llm-a-practical-journey-in-fine-tuning-llama-3-on-turkish-e0ca5b31f2b1?source=rss-69b98f02855------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0ca5b31f2b1</guid>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[peft]]></category>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[lora]]></category>
            <dc:creator><![CDATA[Ogulcanakca]]></dc:creator>
            <pubDate>Sat, 17 May 2025 10:45:13 GMT</pubDate>
            <atom:updated>2025-05-17T10:46:28.044Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Raw Regulations to a Domain-Smart LLM: A Practical Journey in Fine-tuning Llama 3 on Turkish Energy Law</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wYHUuZ7hU5DzGtbaSquwPg.png" /><figcaption>Produced by Chatgpt</figcaption></figure><p>A step-by-step guide on creating a specialized dataset from diverse EPDK documents and performing domain adaptation on Meta Llama 3 8B Instruct using QLoRA.</p><p>Large Language Models (LLMs) like Meta’s Llama 3 have shown incredible capabilities. However, to make them truly effective in specialized fields, such as understanding the nuances of specific legal or regulatory frameworks, domain adaptation fine-tuning is often crucial. This article details my journey in adapting `meta-llama/Meta-Llama-3–8B-Instruct` to the domain of Turkish Energy Market Regulatory Authority (EPDK) legislation. I’ll cover the entire pipeline, from curating a custom dataset from scratch to the fine-tuning process itself, including challenges faced and lessons learned on a resource-constrained environment like Kaggle’s free GPU tier.</p><h3><strong>Phase 1: The Foundation — Dataset Creation and Preprocessing</strong></h3><p>The adage “garbage in, garbage out” couldn’t be more true for LLMs. The quality and relevance of your training data are paramount. My goal was to create a corpus specific to the Turkish energy market.</p><h4>1.1 Sourcing the Data:</h4><p>The initial dataset comprised approximately 3,300 documents related to the EPDK. These documents were in various formats:</p><ul><li>PDFs (many of which were scanned images rather than text-based)</li><li>DOCX files</li><li>Older DOC files</li><li>XLSX files (often containing textual information within cells)</li></ul><p>These documents included laws, regulations, board decisions, communiqués, and other official notices, forming a rich but challenging source for textual data.</p><h4>1.2 The Multi-Format Challenge &amp; Text Extraction:</h4><p>Extracting text from these diverse formats required a multi-pronged approach:</p><ul><li><strong>PDFs:</strong> `PyMuPDF (fitz)` was the primary tool. It’s robust for text-based PDFs.</li><li><strong>DOCX: </strong>The `python-docx` library handled modern Word documents.</li><li><strong>XLSX:</strong> `openpyxl` (or `pandas`) was used to iterate through cells and extract textual content.</li><li><strong>DOC:</strong> Older `.doc` files proved challenging. While `textract` (which often relies on system tools like `antiword` or `wv`) was attempted, it highlighted the difficulties with this legacy format. The most reliable solution for `.doc` files ultimately involved an external batch conversion to `.docx` using Microsoft Word’s COM automation (via a PowerShell script), after which `python-docx` could process them.</li></ul><p><strong>1.3 Tackling Scanned Documents: The OCR Hurdle:</strong></p><p>A significant portion of the PDFs were scanned images. For these, Optical Character Recognition (OCR) was essential.</p><ul><li><strong>Tool:</strong> `pytesseract`, a Python wrapper for Google’s Tesseract OCR engine, was used.</li><li><strong>Process:</strong> For PDFs, `PyMuPDF` was used to render each page as an image, which was then fed to `pytesseract` for text extraction. Language was set to Turkish (`lang=’tur’`).</li><li><strong>Challenge:</strong> OCR quality varied significantly based on the scan quality of the original document. This meant the extracted text from these sources would inevitably contain errors.</li></ul><h4>1.4 NLP Cleaning and Preprocessing — The Iterative Refinement:</h4><p>The raw extracted text (a mix of native and OCR’d content) was noisy. A Python script was developed to perform several cleaning steps:</p><ul><li><strong>Separator Removal:</strong> Custom separators like ` — — NATIVE TEXT — -` and ` — — OCR TEXT — -` (used in my initial extraction script to differentiate sources) were removed.</li><li><strong>Whitespace Normalization: </strong>Multiple spaces and tabs were collapsed to single spaces, leading/trailing whitespace was stripped from lines, and excessive blank lines were reduced (e.g., 3+ newlines to 2).</li><li><strong>Header/Footer Removal:</strong> Regular expressions were used to identify and remove common repeating patterns like dates (“25 Aralık 2021 CUMARTESİ”), “Resmî Gazete”, “Sayı : XXXXX”, and file path/metadata remnants at the bottom of pages (e.g., `ek1_…html[date]`). This required careful pattern crafting and iteration.</li><li><strong>OCR Artifacts &amp; Special Character Correction:</strong> Basic replacements were made for common OCR misinterpretations (e.g., `ÿ` to `ı`, `ƒ` to `ş`, `º` to `ğ`) based on observed patterns.</li><li><strong>Filtering Short/Noisy Lines:</strong> Very short lines or lines primarily consisting of noise were considered for removal.</li></ul><p>This cleaning process was iterative, resulting in a progressively cleaner dataset (e.g., `cleaned_data_v1.jsonl`, `v2`, `v3`).</p><h4><strong>1.5 Structuring and Storing the Cleaned Dataset:</strong></h4><p>The cleaned data was structured into a JSON Lines (`.jsonl`) format. Each line represented a processed document:</p><pre>{&quot;source_file&quot;: &quot;path/to/original_or_converted_file.ext&quot;, &quot;extracted_text&quot;: &quot;The fully cleaned text content...&quot;}</pre><p>This cleaned, but still unchunked, dataset (cleaned_data_v3.jsonl) was then uploaded to the Hugging Face Hub for accessibility and versioning: <a href="https://huggingface.co/datasets/ogulcanakca/epdk_elektrik_piyasasi_mevzuat">ogulcanakca/epdk_elektrik_piyasasi_mevzuat</a>.</p><h3>Phase 2: Preparing Data for Domain Adaptation Fine-tuning</h3><p>With a clean corpus, the next step was to prepare it specifically for domain adaptation fine-tuning with our chosen LLM.</p><p><strong>2.1 Choosing the LLM:</strong> For this project, I selected meta-llama/Meta-Llama-3-8B-Instruct. It&#39;s a powerful open-access model with strong multilingual capabilities and a large context window, making it a good candidate for adapting to a specialized Turkish domain.</p><p><strong>2.2 Tokenizer-Specific Chunking:</strong> LLMs have a maximum context window (Llama 3 8B’s is 8192 tokens). To effectively train the model, long documents need to be broken down into smaller segments (chunks) that fit this window. Crucially, this chunking should be done using the <em>specific tokenizer</em> of the target LLM.</p><ul><li><strong>Tokenizer:</strong> AutoTokenizer.from_pretrained(&quot;meta-llama/Meta-Llama-3-8B-Instruct&quot;) was used.</li><li><strong>Chunk Size:</strong> I opted for CHUNK_SIZE_TOKENS = 2048. While Llama 3 supports 8k, smaller chunks can sometimes be more manageable for training on limited VRAM and can still capture significant context.</li><li><strong>Overlap:</strong> CHUNK_OVERLAP_TOKENS = 200 was used between consecutive chunks to help maintain contextual flow.</li><li><strong>Process:</strong> The cleaned texts were loaded from the Hub dataset, each document’s extracted_text was tokenized, the token IDs were split into overlapping chunks, and each chunk of token IDs was decoded back into text.</li></ul><p><strong>2.3 Final Data Format for Training:</strong> The resulting chunks were formatted into a new JSONL file (epdk_mevzuat_llama3_chunked.jsonl), where each line was:</p><pre>{&quot;text&quot;: &quot;A single text chunk...&quot;}</pre><p>This process yielded approximately 31,271 text chunks, forming the final dataset for fine-tuning.</p><h3>Phase 3: Fine-tuning Llama 3 8B Instruct — Domain Adaptation with QLoRA</h3><p>This phase was performed on a Kaggle Notebook using a free-tier GPU (typically an NVIDIA T4 or P100 with ~16GB VRAM).</p><p><strong>3.1 Environment Setup &amp; Authentication:</strong></p><ul><li><strong>Libraries:</strong> Key libraries installed included transformers, datasets, peft, accelerate, bitsandbytes, and torch. (Note: I encountered torch version compatibility issues that required downgrading to torch==2.5.1 to resolve an ImportError: cannot import name &#39;SLoc&#39;.)</li><li><strong>Authentication:</strong> A Hugging Face token (with write access) was provided via Kaggle Secrets to download the Llama 3 model and my private dataset.</li></ul><p><strong>3.2 Loading the Model (Quantization is Key):</strong> Given the 16GB VRAM constraint, loading an 8B parameter model requires aggressive optimization:</p><ul><li><strong>4-bit Quantization (QLoRA):</strong> BitsAndBytesConfig was used to load the model in 4-bit precision (load_in_4bit=True, bnb_4bit_quant_type=&quot;nf4&quot;, bnb_4bit_compute_dtype=torch.bfloat16).</li><li><strong>No FlashAttention-2:</strong> Initially, I tried enabling attn_implementation=&quot;flash_attention_2&quot; for performance, but the Kaggle GPU (likely P100 or T4) did not have the required Ampere or newer architecture, leading to a RuntimeError. This option was subsequently removed, letting Transformers use a default compatible attention mechanism.</li></ul><pre># Example of model loading config<br>bnb_config = BitsAndBytesConfig(<br>    load_in_4bit=True,<br>    bnb_4bit_quant_type=&quot;nf4&quot;,<br>    bnb_4bit_compute_dtype=torch.bfloat16,<br>    bnb_4bit_use_double_quant=True,<br>)<br>model = AutoModelForCausalLM.from_pretrained(<br>    &quot;meta-llama/Meta-Llama-3-8B-Instruct&quot;,<br>    quantization_config=bnb_config,<br>    device_map=&quot;auto&quot;, # Automatically map to GPU<br>    torch_dtype=torch.bfloat16,<br>    # token=hf_token # Token for model access<br>)</pre><p><strong>3.3 PEFT/LoRA Configuration:</strong> Parameter-Efficient Fine-Tuning (PEFT) with Low-Rank Adaptation (LoRA) was used:</p><ul><li>prepare_model_for_kbit_training(model) prepared the quantized model.</li><li>LoraConfig was defined with r=16, lora_alpha=32, lora_dropout=0.05, and target_modules=[&quot;q_proj&quot;, &quot;k_proj&quot;, &quot;v_proj&quot;, &quot;o_proj&quot;, &quot;gate_proj&quot;, &quot;up_proj&quot;, &quot;down_proj&quot;].</li><li>get_peft_model(model, lora_config) applied the LoRA layers. This resulted in only ~0.52% of total parameters being trainable.</li></ul><p><strong>3.4 Training Arguments &amp; Trainer:</strong> Standard transformers.TrainingArguments were configured:</p><ul><li>output_dir: For saving checkpoints and the final adapter.</li><li>per_device_train_batch_size=1, gradient_accumulation_steps=8 (effective batch size of 8).</li><li>learning_rate=2e-4.</li><li>max_steps=200 (This was for an initial trial run; a full domain adaptation would require many more steps, e.g., at least one full epoch over ~31k chunks).</li><li>logging_steps=10, save_steps=50.</li><li>bf16=True (as torch_dtype and bnb_4bit_compute_dtype were bfloat16).</li><li>optim=&quot;paged_adamw_8bit&quot;.</li><li>gradient_checkpointing=True (essential for memory saving, though it slows down training).</li></ul><p>A DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False) was used with the standard transformers.Trainer.</p><p><strong>3.5 Launching and Monitoring Training:</strong> The training was initiated with trainer.train().</p><ul><li>The message “use_cache=True is incompatible with gradient checkpointing. Setting use_cache=False.&quot; is normal and expected.</li><li>The trial run of 200 steps took approximately <strong>8.5 hours</strong>, indicating a very slow step time (~154 seconds/step). This highlighted the performance limitations of free-tier Kaggle GPUs for such a task without optimizations like FlashAttention-2.</li><li>Training loss showed a slight downward trend, starting around 2.2–2.3 and ending around 2.15.</li></ul><p><strong>3.6 Saving the Adapter:</strong> Upon completion, trainer.save_model(output_dir) saved the trained LoRA adapter weights, tokenizer configuration, and training state to the specified directory.</p><h3>Phase 4: Sharing the Fine-tuned Adapter</h3><p>The resulting adapter was then uploaded to the Hugging Face Hub: <a href="https://huggingface.co/ogulcanakca/llama3-8b-epdk-domain-adapter-v1">ogulcanakca/llama3-8b-epdk-domain-adapter-v1</a> This allows it to be easily loaded and used by others (or by myself in different environments). The Python code snippet in the Model Card on the Hub demonstrates how to load and use it.</p><h3>Challenges Encountered &amp; Lessons Learned</h3><p>This project, while ultimately a successful learning exercise, came with its share of challenges:</p><ol><li><strong>Legacy </strong><strong>.doc Files:</strong> Extracting text from old .doc files directly in Python is unreliable. External conversion (e.g., using MS Word COM or LibreOffice CLI) to .docx before Python processing is highly recommended.</li><li><strong>Hardware Limitations for Optimizations:</strong> The desire to use flash_attention_2 for speed was thwarted by the available GPU architecture on Kaggle&#39;s free tier. This highlights that access to specific hardware (Ampere+ GPUs) is needed for some SOTA optimizations.</li><li><strong>Library Versioning &amp; Compatibility:</strong> I encountered several ImportError and TypeError issues (e.g., SLoc not found in torch._guards, SFTTrainer argument mismatches). These were mostly resolved by carefully managing library versions, especially torch, and sometimes switching to more standard components like transformers.Trainer. Always ensure your core libraries (PyTorch, Transformers, Accelerate, PEFT) are compatible.</li><li><strong>Training Speed on Limited GPUs:</strong> The ~8.5 hours for just 200 steps with Llama 3 8B (QLoRA, grad checkpointing, no FlashAttention) on a Kaggle T4/P100 underscores the significant time commitment needed for meaningful fine-tuning on free-tier hardware.</li><li><strong>OCR Imperfections:</strong> Even after cleaning, the initial sample chunk showed that OCR is not perfect. For high-stakes applications, the quality of OCR’d text needs thorough validation, or alternative data sources might be preferable.</li><li><strong>Iterative Process:</strong> Dataset cleaning and fine-tuning script development are highly iterative. Expect to go back and forth, refining steps based on errors and observations.</li></ol><h3>Conclusion &amp; Next Steps</h3><p>This project successfully navigated the end-to-end process of creating a domain-specific dataset from diverse document formats and fine-tuning a state-of-the-art LLM (Llama 3 8B Instruct) using QLoRA for domain adaptation. A LoRA adapter was created and shared, and valuable lessons were learned about data preprocessing, library management, and the practicalities of fine-tuning on resource-constrained environments.</p><p>The 200-step training was primarily a proof-of-concept for the pipeline. For this adapter to be genuinely impactful in understanding EPDK texts, <strong>next steps</strong> would include:</p><ul><li><strong>More Extensive Training:</strong> Fine-tuning for at least one full epoch (around 3900 steps for this dataset and batch size), or even more, is necessary. This would likely require more powerful GPUs (like those on GCP, which I plan to explore) or a significantly longer time commitment on Kaggle.</li><li><strong>Systematic Evaluation:</strong> Implementing quantitative evaluation (e.g., perplexity on a domain-specific test set, performance on downstream NLP tasks like Q&amp;amp;A or summarization relevant to EPDK) to measure the actual impact of domain adaptation.</li><li><strong>Exploring Instruction Tuning:</strong> Using the domain-adapted model as a base for further instruction fine-tuning on EPDK-specific question-answer pairs or tasks.</li></ul><p>This journey underscores the power of fine-tuning to specialize LLMs and the critical importance of careful data preparation. While challenges exist, the open-source ecosystem around Hugging Face provides incredible tools to tackle them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0ca5b31f2b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Advanced Agentic AI Chatbot: A Deep Dive into a Supervisor-Based Multi-Agent…]]></title>
            <link>https://medium.com/@ogulcanakca/building-an-advanced-agentic-ai-chatbot-a-deep-dive-into-a-supervisor-based-multi-agent-ef5e4827e00e?source=rss-69b98f02855------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef5e4827e00e</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ogulcanakca]]></dc:creator>
            <pubDate>Thu, 15 May 2025 11:40:26 GMT</pubDate>
            <atom:updated>2025-05-17T10:56:17.825Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an Advanced Agentic AI Chatbot: A Deep Dive into a Supervisor-Based Multi-Agent Architecture with LangGraph</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e6AX2s0qFZp-TPGbCVvp2A.jpeg" /><figcaption>Produced by Canva AI</figcaption></figure><p>The realm of Artificial Intelligence is rapidly advancing, with agentic AI systems and multi-agent collaborations at the forefront of innovation. These systems are moving beyond simple task execution to handle complex, multi-faceted queries by leveraging specialized intelligent agents. This article delves into the “Agentic AI Chatbot Project,” a compelling case study that showcases a sophisticated supervisor-based multi-agent AI chatbot. We will explore its architecture, diverse capabilities, the cutting-edge technologies that power it, and illustrative code snippets to offer insights into building robust and intelligent conversational AI.</p><h3>Core Concept: The Power of Supervisor-Based Multi-Agent Systems</h3><p>At the heart of this chatbot lies a <strong>supervisor-based multi-agent architecture</strong>. This design paradigm centers around a <strong>supervisor agent</strong>, which acts as an intelligent router. As detailed in the project’s README.md and implemented in app/agents/supervisor.py, this supervisor meticulously analyzes incoming user queries to classify their topic and intent.</p><p>The supervisor’s core logic involves prompting a Language Model (LLM) to categorize the query. Here’s a glimpse into the classification prompt template from configs/agent_config.py:</p><pre># configs/agent_config.py (Excerpt)<br>CLASSIFICATION_PROMPT_TEMPLATE = &quot;&quot;&quot;Your task is to analyze the user query below and classify it into one of the following five categories:1.  **Resmi Gazete**: Questions seeking information on regulations...<br>     * Examples: &quot;When was the latest omnibus bill passed?&quot;...<br> 2.  **News**: Questions about current events, news (politics, economy, sports, entertainment)...<br>     * Examples: &quot;What&#39;s the weather like in Izmir tomorrow?&quot;...<br> 3.  **Travel**: Questions about travel planning, flights, hotels, destinations, itineraries, or travel tips.<br> 4.  **Belge Sorusu**: Clearly document-related queries-either about a previously uploaded document or a follow-up referencing it...<br> 5.  **Other**: All other queries not fitting into the above categories...<br>User Query:<br>&quot;{query}&quot;<br>Evaluate carefully and provide ONLY and EXACTLY one of the **five** category names (&#39;Resmi Gazete&#39;, &#39;News&#39;, &#39;Travel&#39;, &#39;Belge Sorusu&#39;, &#39;Other&#39;) as the answer.<br>Category:&quot;&quot;&quot;</pre><p>Based on this classification (e.g., “Resmi Gazete,” “News/General Knowledge,” “Travel Planning,” “Uploaded Document Query,” or “Other”), it then routes the query to the most appropriate specialized agent for handling. This routing is managed within the LangGraph framework, as seen in app/graph.py:</p><pre># app/graph.py (Excerpt)<br>def route_based_on_classification(state: AgentState) -&gt; str:<br>    if state.get(&quot;route_directly_to_agentic_rag&quot;):<br>        logging.info(f&quot;[Router] Direct routing flag detected. Routing to: &#39;{NODE_AGENTIC_RAG}&#39;&quot;)<br>        return NODE_AGENTIC_RAG<br>    classification_result = state.get(&quot;classification&quot;)<br>    logging.info(f&quot;[Router] Routing based on classification result: &#39;{classification_result}&#39;&quot;)<br>    if classification_result == &quot;Resmi Gazete&quot;:<br>        return NODE_RESMI_GAZETE<br>    elif classification_result == &quot;News&quot;:<br>        return NODE_NEWS<br>    elif classification_result == &quot;Travel&quot;:<br>        return NODE_TRAVEL<br>    elif classification_result == BELGE_SORUSU_CATEGORY: # Defined in app_config.py<br>        logging.info(f&quot;[Router] Classification &#39;{BELGE_SORUSU_CATEGORY}&#39;. Routing to: &#39;{NODE_AGENTIC_RAG}&#39;&quot;)<br>        return NODE_AGENTIC_RAG<br>    else:<br>        logging.warning(f&quot;Unexpected or &#39;Other&#39; classification &#39;{classification_result}&#39;. Routing to fallback.&quot;)<br>        return NODE_FALLBACK</pre><p>This approach offers several advantages:</p><ul><li><strong>Modularity:</strong> Each agent is a self-contained unit.</li><li><strong>Specialization:</strong> Agents are fine-tuned for specific domains.</li><li><strong>Robustness:</strong> Failures can be isolated or handled by a fallback.</li><li><strong>Scalability:</strong> New capabilities can be added by integrating new agents.</li></ul><h3>Key Capabilities and the Specialized Agent Ecosystem</h3><p>The chatbot boasts a rich set of functionalities, each managed by one or more specialized agents:</p><p><strong>Official Gazette (Resmi Gazete) Querying (RAG):</strong></p><ul><li><strong>Agent:</strong> The resmi_gazete_agent (in app/agents/resmi_gazete_agent.py).</li><li><strong>Technology:</strong> Employs Retrieval-Augmented Generation (RAG) over Turkish Official Gazette documents stored in a ChromaDB vector database. The intfloat/multilingual-e5-large model is used for embeddings.</li><li><strong>Data Flow:</strong> Raw documents from data/raw/resmi_gazete/ are processed (chunked) into data/processed/resmi_gazete/, and their embeddings are stored in data/embeddings/.</li></ul><p><strong>Implementation Snippet (RAG Logic):</strong></p><pre># app/agents/resmi_gazete_agent.py (Conceptual Excerpt)<br># ... (imports and setup) ...<br>retrieved_docs = retrieve_documents(<br>    query=query,<br>    collection_name=RESMI_GAZETE_COLLECTION, # from agent_config<br>    n_results=NUM_DOCUMENTS_TO_RETRIEVE     # from agent_config<br>)<br>if not retrieved_docs:<br>    # ... (handle no documents found) ...<br>else:<br>    retrieved_context = format_context(retrieved_docs)<br>    llm = get_llm()<br>    prompt = PROMPT_TEMPLATE.format(query=query, context=retrieved_context) # from agent_config<br>    llm_response = llm.invoke(prompt)<br>    final_answer = llm_response.content.strip()<br># ... (return answer and context) ...</pre><ul><li><strong>User Interaction:</strong> Provides answers with source context.</li></ul><p><strong>News and General Knowledge:</strong></p><ul><li><strong>Agent:</strong> The news_agent (in app/agents/news_agent.py).</li><li><strong>Technology:</strong> A ReAct (Reasoning and Acting) agent using tools like web search (Tavily/DuckDuckGo) and Wikipedia (from app/tools/external_apis.py). The ReAct prompt is defined in configs/agent_config.py (either pulled from Langchain Hub or a manual template).</li><li><strong>Tool Definition Snippet:</strong></li></ul><pre># app/tools/external_apis.py (Excerpt)<br>from langchain.tools import Tool<br><br>wikipedia_tool = Tool(<br>    name=&quot;WikipediaSearch&quot;,<br>    func=search_wikipedia, # Custom function to call wikipedia API<br>    description=&quot;Used to get encyclopedic information...&quot;<br>)<br><br>web_search_tool = Tool(<br>    name=&quot;WebSearch&quot;,<br>    func=search_web, # Custom function using Tavily or DuckDuckGo<br>    description=&quot;Performs web searches for up-to-date events...&quot;<br>)</pre><ul><li><strong>Data Flow:</strong> News from TRT Haber RSS (via scripts/news_fetcher.py) is processed.</li></ul><p><strong>Travel Planning:</strong></p><ul><li><strong>Agent:</strong> The travel_agent (in app/agents/travel_agent.py) initiates a complex sub-workflow.</li><li><strong>Sub-Workflow (</strong>app/travel_system/workflow.py<strong>):</strong> A LangGraph-based system with its own agents (coordinator_agent, date_budget_agent, destination_agent) and tools (budget_tools, date_tools, destination_tools, parsing_tools). For example, the parse_travel_query tool in app/travel_system/tools/parsing_tools.py uses an LLM with a Pydantic model to structure user input:</li><li>Python</li></ul><pre># app/travel_system/tools/parsing_tools.py (Pydantic Model Excerpt)<br>from pydantic import BaseModel, Field<br>from typing import Optional<br><br>class TravelQuery(BaseModel):<br>    origin: Optional[str] = Field(None, description=&quot;The starting city...&quot;)<br>    destination: str = Field(..., description=&quot;The city or place...&quot;)<br>    natural_language_date: str = Field(..., description=&quot;The user&#39;s description of the travel start date...&quot;)<br>    duration_days: int = Field(..., description=&quot;The duration of the stay in days...&quot;)<br>    budget_amount: Optional[float] = Field(None, description=&quot;The user&#39;s approximate budget amount...&quot;)<br>    budget_currency: Optional[str] = Field(None, description=&quot;The currency of the user&#39;s budget...&quot;)<br>    error: Optional[str] = Field(None, description=&quot;Error message if parsing fails...&quot;)</pre><ul><li><strong>Output:</strong> Can generate detailed travel plans, optionally as PDF files using app/travel_system/utils/pdf_saver.py with DejaVuSansCondensed fonts from assets/fonts/.</li><li><strong>External APIs:</strong> Uses OpenWeatherMap, TomTom Maps, ExchangeRate-API.</li></ul><p><strong>Agentic RAG (Uploaded Document Querying):</strong></p><ul><li><strong>Agent:</strong> The agentic_rag_agent (in app/agents/agentic_rag_agent.py).</li><li><strong>Functionality:</strong> Users can upload documents (PDF, TXT, DOCX, etc., as defined in LOADER_MAPPING in configs/app_config.py). The agent processes these and answers questions based on their content using RAG.</li><li><strong>Implementation Snippet (RAG Chain for Uploaded Docs):</strong></li></ul><pre># app/agents/agentic_rag_agent.py (Conceptual Excerpt)<br># ... (load document, split into chunks) ...<br>embeddings = GoogleGenerativeAIEmbeddings(model=&quot;models/embedding-001&quot;, google_api_key=gemini_api_key)<br>vectorstore = Chroma.from_documents(documents=chunks, embedding=embeddings)<br>retriever = vectorstore.as_retriever(search_type=&quot;similarity&quot;, search_kwargs={&#39;k&#39;: 5})<br><br>llm = get_llm(temperature=0.2)<br>prompt = ChatPromptTemplate.from_template(RAG_PROMPT_TEMPLATE) # from agent_config<br><br>rag_chain = (<br>    {&quot;context&quot;: retriever, &quot;question&quot;: RunnablePassthrough()}<br>    | prompt<br>    | llm<br>    | StrOutputParser()<br>)<br>answer = rag_chain.invoke(query)<br># ... (return answer and context) ...</pre><ul><li><strong>Embedding Model:</strong> Uses models/embedding-001.</li></ul><p><strong>Fallback Mechanism:</strong></p><ul><li><strong>Agent:</strong> The fallback_agent (in app/agents/fallback_agent.py).</li><li><strong>Functionality:</strong> Provides a standard response (FALLBACK_RESPONSE from configs/agent_config.py) for out-of-scope queries.</li></ul><h3>Technological Stack Powering the Chatbot</h3><ul><li><strong>Programming Language:</strong> Python.</li><li><strong>Orchestration &amp; Agent Framework:</strong> LangChain &amp; LangGraph. The main graph definition in app/graph.py wires together the agents.</li></ul><pre># app/graph.py (Excerpt of Graph Definition)<br>workflow = StateGraph(AgentState)<br><br>workflow.add_node(NODE_SUPERVISOR, classify_query)<br>workflow.add_node(NODE_RESMI_GAZETE, generate_resmi_gazete_answer)<br># ... other agent nodes<br>workflow.add_node(NODE_AGENTIC_RAG, handle_uploaded_doc_query)<br><br>workflow.set_entry_point(NODE_SUPERVISOR)<br>workflow.add_conditional_edges(<br>    NODE_SUPERVISOR,<br>    route_based_on_classification,<br>    { # Mapping classification to next node<br>        NODE_RESMI_GAZETE: NODE_RESMI_GAZETE,<br>        NODE_NEWS: NODE_NEWS,<br>        # ... other routes<br>        NODE_AGENTIC_RAG: NODE_AGENTIC_RAG<br>    }<br>)<br># ... add terminal edges<br>graph_app = workflow.compile()</pre><ul><li><strong>User Interface:</strong> Streamlit (app/ui/streamlit_app.py).</li><li><strong>Language Model (LLM):</strong> Google Gemini (e.g., Gemini 1.5 Flash), configured in app/core/llm.py.</li></ul><pre># app/core/llm.py (Excerpt)<br>from langchain_google_genai import ChatGoogleGenerativeAI<br># ... (logging, imports) ...<br>def get_llm(<br>    model_name: str = &quot;gemini-1.5-flash-latest&quot;,<br>    temperature: float = 0.5,<br>    # ... other parameters<br>) -&gt; Optional[ChatGoogleGenerativeAI]:<br>    gemini_api_key = os.getenv(&quot;GEMINI_API_KEY&quot;)<br>    if not gemini_api_key:<br>        logging.error(&quot;Environment variable &#39;GEMINI_API_KEY&#39; not found or is empty!&quot;)<br>        return None<br>    # ... (caching logic) ...<br>    try:<br>        llm = ChatGoogleGenerativeAI(<br>            model=model_name,<br>            google_api_key=gemini_api_key,<br>            temperature=temperature,<br>            # ... other settings<br>        )<br>        # ... (add to cache) ...<br>        return llm<br>    except Exception as e:<br>        logging.error(f&quot;Error occurred while creating LLM instance: {e}&quot;, exc_info=True)<br>        return None</pre><ul><li><strong>Embedding Models:</strong> intfloat/multilingual-e5-large (classic RAG) &amp; models/embedding-001 (Agentic RAG). Model names are specified in configs/app_config.py.</li><li><strong>Vector Database:</strong> ChromaDB, managed via app/storage/database.py.</li></ul><pre># app/storage/database.py (Excerpt for collection creation)<br>import chromadb<br>from chromadb.utils import embedding_functions<br># ...<br>def get_or_create_collection(collection_name: str, embedding_model_name: str = MODEL_NAME) -&gt; Optional[chromadb.Collection]:<br>    client = get_chroma_client() # Gets a persistent client<br>    emb_func = get_embedding_function(embedding_model_name) # Uses SentenceTransformer<br>    collection = client.get_or_create_collection(<br>        name=collection_name,<br>        embedding_function=emb_func,<br>        metadata={&quot;hnsw:space&quot;: &quot;cosine&quot;}<br>    )<br>    return collection</pre><ul><li><strong>External APIs:</strong> Tavily/DuckDuckGo, Wikipedia, Google Serper, OpenWeatherMap, TomTom Maps, ExchangeRate-API.</li><li><strong>Containerization:</strong> Docker &amp; Docker Compose (Dockerfile, docker-compose.yml).</li></ul><h3>Data Pipeline: From Raw Information to Actionable Knowledge</h3><ul><li><strong>Data Fetching:</strong> Scripts like scripts/news_fetcher.py (for TRT Haber RSS) and scripts/resmi_news_fetcher.py (for Resmi Gazete from AA) gather raw data into data/raw/.</li><li><strong>Data Processing:</strong> scripts/process_data.py processes this raw data.</li></ul><pre># scripts/process_data.py (Conceptual Excerpt)<br>from app.utils.text_processing import split_text<br># ...<br>for item_index, item_data in enumerate(data_list):<br>    text_content = item_data.get(&#39;text&#39;)<br>    # ... (error handling and metadata extraction) ...<br>    chunks = split_text(text_content, CHUNK_SIZE, CHUNK_OVERLAP) # from script_config<br>    for chunk_index, chunk_text in enumerate(chunks):<br>        chunk_id = f&quot;{generate_unique_id(item_data, file_stem, item_index)}_{chunk_index}&quot;<br>        processed_chunks.append({<br>            &quot;id&quot;: chunk_id,<br>            &quot;text&quot;: chunk_text,<br>            &quot;metadata&quot;: metadata.copy()<br>        })<br># ... (save processed_chunks to data/processed/) ...</pre><ul><li><strong>Embedding Generation &amp; Storage:</strong> scripts/generate_embeddings.py converts text chunks from data/processed/ into vector embeddings using models defined in app/utils/embedding.py and stores them in ChromaDB.</li></ul><pre># app/utils/embedding.py (Conceptual Excerpt)<br>from sentence_transformers import SentenceTransformer<br># ...<br>model: Optional[SentenceTransformer] = None<br>def get_embedding_model() -&gt; SentenceTransformer:<br>    global model<br>    if model is None:<br>        device = &#39;cuda&#39; if torch.cuda.is_available() else (&#39;mps&#39; if torch.backends.mps.is_available() else &#39;cpu&#39;)<br>        model = SentenceTransformer(MODEL_NAME, device=device) # MODEL_NAME from app_config<br>    return model<br><br>def generate_embeddings(texts: List[str], batch_size: int = 64) -&gt; List[List[float]]:<br>    model = get_embedding_model()<br>    embeddings_np = model.encode(texts, batch_size=batch_size, show_progress_bar=True)<br>    return embeddings_np.tolist()</pre><h3>System Architecture with LangGraph: Orchestrating Intelligent Agents</h3><p>The chatbot’s architecture, visualized in chatbot-architecture.png, is orchestrated using LangGraph (app/graph.py).</p><ul><li><strong>AgentState:</strong> The central AgentState (from app/core/state.py) carries data between graph nodes.</li></ul><pre># app/core/state.py<br>from typing import Optional, TypedDict<br><br>class AgentState(TypedDict):<br>    query: str<br>    classification: Optional[str]<br>    context: Optional[str]<br>    answer: Optional[str]<br>    source: Optional[str]<br>    pdf_path: Optional[str]<br>    uploaded_file_data: Optional[bytes]<br>    uploaded_file_name: Optional[str]<br>    route_directly_to_agentic_rag: Optional[bool]</pre><ul><li><strong>Nodes and Edges:</strong> Nodes represent agents, and conditional edges (based on the supervisor’s classification or route_directly_to_agentic_rag flag) direct the workflow.</li><li><strong>Travel Sub-Workflow:</strong> The travel_agent node contains its own nested LangGraph for detailed travel planning, showcasing modular and hierarchical agent design.</li></ul><h3>Configuration Management: Tailoring Agent Behavior</h3><p>The configs/ directory centralizes configurations:</p><ul><li>agent_config.py: Agent prompts (like CLASSIFICATION_PROMPT_TEMPLATE, REACT_HUB_PROMPT_PATH, PROMPT_TEMPLATE for RAG, travel agent system messages), routing categories, RAG settings.</li><li>api_config.py: Logic for loading API keys from .env using python-dotenv.</li><li>app_config.py: Application settings like ChromaDB path, model names (e.g., MODEL_NAME), LangGraph node names (NODE_SUPERVISOR, etc.), LOADER_MAPPING for document types, and CITY_CURRENCY_MAP.</li><li>script_config.py: Paths, URLs, and parameters for data processing scripts.</li></ul><h3>Running the Chatbot: Local and Dockerized Deployment</h3><ul><li><strong>Local Environment:</strong> Involves setting up a Python environment, installing dependencies (requirements.txt), configuring API keys in .env, optionally running data preparation scripts, and launching with streamlit run app/ui/streamlit_app.py.</li><li><strong>Docker Environment:</strong> Utilizes docker-compose.yml and Dockerfile for containerized deployment.</li><li>YAML</li></ul><pre># docker-compose.yml (Abbreviated)<br>version: &#39;3.8&#39;<br>services:<br>  chatbot-app:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    container_name: agentic_chatbot_container<br>    ports:<br>      - &quot;8501:8501&quot;<br>    env_file:<br>      - .env<br>    volumes:<br>      - chroma_data:/app/data/embeddings<br>      # ... other volumes<br>volumes:<br>  chroma_data: {}<br>  # ...</pre><ul><li>The Dockerfile prepares the Python environment and copies necessary application files.</li></ul><h3>User Interaction: A Seamless Conversational Experience</h3><p>The Streamlit UI (app/ui/streamlit_app.py) facilitates interaction:</p><ul><li>Users input questions.</li><li>The chatbot provides answers, citing the source agent.</li><li>RAG context is expandable.</li><li>Document upload for Agentic RAG is available.</li></ul><pre># app/ui/streamlit_app.py (Conceptual Snippet for invoking graph)<br>if user_input := st.chat_input(&quot;Type your question here...&quot;):<br>    # ... (append to chat history) ...<br>    with st.spinner(&quot;Preparing response...&quot;):<br>        graph_input = {<br>            &quot;query&quot;: user_input,<br>            &quot;chat_history&quot;: formatted_history # from st.session_state<br>        }<br>        if st.session_state.get(&quot;new_upload_triggered&quot;):<br>            graph_input[&quot;route_directly_to_agentic_rag&quot;] = True<br>            st.session_state.new_upload_triggered = False<br>        # ...<br>        final_state = graph_app.invoke(graph_input) # graph_app from app.graph<br>        answer = final_state.get(&quot;answer&quot;, &quot;...&quot;)<br>        source = final_state.get(&quot;source&quot;, &quot;...&quot;)<br>        # ... (display answer, source, context, PDF download) ...</pre><ul><li>Travel plans can be downloaded as PDFs.</li><li>Chat history can be cleared.</li></ul><h3>Future Directions and Conclusion</h3><p>The Agentic AI Chatbot project exemplifies a powerful and flexible supervisor-based multi-agent architecture using LangChain and LangGraph. It adeptly integrates specialized agents, diverse data sources, and external tools to offer a rich conversational experience.</p><p>The project’s README.md notes potential enhancements, such as adding <strong>agent memory</strong> for more contextually continuous dialogues.</p><p>This detailed exploration provides a solid blueprint for crafting sophisticated AI chatbots. By embracing specialized agents, modular design, and robust orchestration frameworks like LangGraph, developers are well-equipped to build the next generation of intelligent, adaptable, and highly capable conversational AI systems. The journey into agentic AI is dynamic, and this project serves as an inspiring milestone.</p><p>Github Repository: <a href="https://github.com/ogulcanakca/agentic-chatbot">Link</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef5e4827e00e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Harnessing the Power of AI Agents: A Deep Dive into Seamless Service Integration with FastAgent and…]]></title>
            <link>https://medium.com/@ogulcanakca/harnessing-the-power-of-ai-agents-a-deep-dive-into-seamless-service-integration-with-fastagent-and-5c914af326f6?source=rss-69b98f02855------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c914af326f6</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Ogulcanakca]]></dc:creator>
            <pubDate>Thu, 15 May 2025 11:05:38 GMT</pubDate>
            <atom:updated>2025-05-17T11:11:27.852Z</atom:updated>
            <content:encoded><![CDATA[<h3>Harnessing the Power of AI Agents: A Deep Dive into Seamless Service Integration with FastAgent and MCP Servers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mQvwoKlMc5i5jjp46dk-_w.jpeg" /></figure><p>In the rapidly evolving landscape of Artificial Intelligence, agents are becoming increasingly sophisticated, capable of performing complex tasks and interacting with a multitude of external services. However, establishing seamless, standardized communication between these AI agents and diverse external systems presents a significant challenge. This is where the Model Context Protocol (MCP) and orchestration clients like FastAgent step in, offering a robust framework for building intelligent, interconnected AI solutions.</p><p>This article explores a practical implementation that leverages FastAgent to interact with various services through MCP servers. We’ll delve into the architecture, configured services, and the agent ecosystem of this project, showcasing how such an integration can lead to a rich, interactive, and comprehensively connected user experience while adhering to best practices in agent-based system design.</p><h3>Understanding the Core Components: MCP Servers and FastAgent</h3><p>At its heart, the <strong>Model Context Protocol (MCP)</strong> provides a standardized way for AI agents to communicate with external systems. Think of MCP servers as specialized intermediaries that expose the functionalities of various services — from capturing screenshots and querying weather information to sending emails and managing databases — in a way that AI agents can uniformly understand and interact with.</p><p>For instance, in the project’s fastagent.config.yaml file, an MCP server like the &quot;filesystem&quot; server is configured as follows:</p><pre># fastagent.config.yaml (Filesystem MCP Server Excerpt)<br>mcp:<br>    servers:<br>        filesystem:<br>            command: &quot;npx&quot;<br>            args: [&quot;-y&quot;, &quot;@modelcontextprotocol/server-filesystem&quot;, &quot;.&quot;]</pre><p>This configuration tells FastAgent how to launch and communicate with the filesystem MCP server, enabling the AI agent to interact with local files.</p><p><strong>FastAgent</strong> is the client-side orchestrator in this ecosystem. It is responsible for managing the interactions between the primary AI agent and the array of MCP servers. FastAgent facilitates seamless communication and data exchange, allowing the agent to leverage the capabilities of connected services efficiently.</p><h3>A Look Inside: Project Architecture and Configured Services</h3><p>The project we’re examining is structured to integrate a variety of MCP servers, each providing a distinct functionality. The configuration for these servers is primarily managed within the fastagent.config.yaml file, with sensitive information like API keys stored securely in fastagent.secrets.yaml or environment variables.</p><p>Let’s explore the key MCP servers configured in this project:</p><ul><li><strong>Filesystem MCP Server:</strong></li><li><strong>Purpose:</strong> Enables interaction with the local filesystem.</li><li><strong>Implementation:</strong> Utilizes an npx command to run the @modelcontextprotocol/server-filesystem package.</li><li><strong>Benefit:</strong> Allows the AI agent to read, write, and manage files and directories, crucial for tasks involving data persistence, local configuration management, or processing local documents.</li></ul><p><strong>Google Maps MCP Server:</strong></p><ul><li><strong>Purpose:</strong> Provides access to Google Maps services.</li><li><strong>Implementation:</strong> Runs the @modelcontextprotocol/server-google-maps package via npx. Requires a Google Maps API Key, which should be configured with necessary Maps APIs (Places, Directions, Geocoding, etc.) enabled in the Google Cloud Platform project. The OAuth keys are managed via a gcp-oauth.keys.json file.</li><li><strong>Benefit:</strong> Empowers the agent with a wide range of location-based capabilities, including geocoding addresses, finding places, calculating routes and distances, and retrieving elevation data.</li></ul><p><strong>Slack MCP Server:</strong></p><ul><li><strong>Purpose:</strong> Facilitates communication and interaction with Slack workspaces.</li><li><strong>Implementation:</strong> Uses the @modelcontextprotocol/server-slack package via npx, requiring a Slack Bot Token, Team ID, and relevant Channel IDs.</li><li><strong>Benefit:</strong> Allows the agent to participate in Slack conversations, such as listing channels, sending messages, replying in threads, reacting with emojis, fetching message history, and retrieving user information, all in Turkish.</li></ul><p><strong>SQLite MCP Server:</strong></p><ul><li><strong>Purpose:</strong> Offers an interface to interact with an SQLite database.</li><li><strong>Implementation:</strong> Runs a local Python-based MCP server (mcp-server-sqlite) using uv (a Python package installer and virtual environment manager), targeting a test.db file located in ./src/sqlite/. The server itself defines tools for database operations like read_query, write_query, create_table, list_tables, describe_table, and append_insight.</li><li>The server itself, detailed in src/sqlite/src/mcp_server_sqlite/server.py, defines tools like read_query and create_table:</li></ul><pre># src/sqlite/src/mcp_server_sqlite/server.py (Tool Listing Excerpt)<br># ... (inside handle_list_tools async def)<br>return [<br>    types.Tool(<br>        name=&quot;read_query&quot;,<br>        description=&quot;Execute a SELECT query on the SQLite database&quot;,<br>        inputSchema={<br>            &quot;type&quot;: &quot;object&quot;,<br>            &quot;properties&quot;: {<br>                &quot;query&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;SELECT SQL query to execute&quot;},<br>            },<br>            &quot;required&quot;: [&quot;query&quot;],<br>        },<br>    ),<br>    types.Tool(<br>        name=&quot;create_table&quot;,<br>        description=&quot;Create a new table in the SQLite database&quot;,<br>        # ... inputSchema ...<br>    ),<br>    # ... other tools like list_tables, describe_table, append_insight<br>]</pre><ul><li><strong>Benefit:</strong> Enables the agent to perform complex database operations, including executing SQL queries, managing table schemas, and extracting structured data for analysis or reporting, with responses in Turkish.</li></ul><p><strong>Screenshot Capture MCP Server:</strong></p><ul><li><strong>Purpose:</strong> Provides the functionality to capture screenshots of the user’s screen.</li><li><strong>Implementation:</strong> A custom local Python script (./created_mcp_servers/screenshot_capture.py) executed directly. The script uses the mss library to capture the screen and FastMCP to define the tool.</li></ul><pre># created_mcp_servers/screenshot_capture.py (Tool Definition Excerpt)<br>from mcp.server.fastmcp import FastMCP<br>import mss<br>import base64<br># ...<br><br>mcp = FastMCP(&quot;screenshot_capture&quot;)<br><br>@mcp.tool()<br>async def capture_screenshot(save_path: str = &quot;screenshot.png&quot;) -&gt; Dict[str, str]:<br>    &quot;&quot;&quot;<br>    Capture a full-screen screenshot and return it as a base64-encoded PNG string.<br>    Returns:<br>        A dict with key &quot;image_base64&quot; containing the PNG image data.<br>    &quot;&quot;&quot;<br>    with mss.mss() as sct:<br>        screenshot = sct.grab(sct.monitors[0])<br>        png_bytes = mss.tools.to_png(screenshot.rgb, screenshot.size)<br>    # ... (save file and prepare response) ...<br>    b64 = base64.b64encode(png_bytes).decode(&quot;utf-8&quot;)<br>    return {&quot;saved_to&quot;: save_path, &quot;image_base64&quot;: b64}</pre><ul><li><strong>Benefit:</strong> Useful for tasks requiring visual context from the user’s screen, such as debugging, documentation, or providing visual feedback.</li></ul><p><strong>Weather API MCP Server:</strong></p><ul><li><strong>Purpose:</strong> Delivers weather information for any specified city.</li><li><strong>Implementation:</strong> A local Python script (./created_mcp_servers/weather_api.py) that interacts with an external weather API (e.g., OpenWeatherMap, requiring an API key). The script uses aiohttp for asynchronous API calls and FastMCP.</li></ul><pre># created_mcp_servers/weather_api.py (Tool Definition Excerpt)<br>from mcp.server.fastmcp import FastMCP<br>import aiohttp<br># ...<br><br>mcp = FastMCP(&quot;weather_api&quot;)<br>OPENWEATHER_API_KEY = &quot;OPENWEATHER_API_KEY&quot; # Placeholder, real key from env<br><br>@mcp.tool()<br>async def get_weather(city: str, country_code: Optional[str] = None) -&gt; Dict:<br>    &quot;&quot;&quot;<br>    OpenWeather API kullanarak hava durumu bilgilerini alır.<br>    Args:<br>        city: Şehir adı<br>        country_code: Ülke kodu (örn. &quot;TR&quot;, &quot;US&quot;)<br>    Returns:<br>        Hava durumu bilgilerini içeren bir sözlük<br>    &quot;&quot;&quot;<br>    # ... (API call logic using aiohttp) ...<br>    async with aiohttp.ClientSession() as session:<br>        async with session.get(url) as response:<br>            # ... (process response) ...</pre><ul><li><strong>Benefit:</strong> Allows the agent to provide real-time weather updates, enhancing its utility for planning or informational queries.</li></ul><p><strong>Serper Search MCP Server:</strong></p><ul><li><strong>Purpose:</strong> Enables the agent to perform internet searches using the Serper API and retrieve results.</li><li><strong>Implementation:</strong> A local Python script (./created_mcp_servers/serper_search.py) that requires a Serper API key. It uses aiohttp and FastMCP.</li></ul><pre># created_mcp_servers/serper_search.py (Tool Definition Excerpt)<br>from mcp.server.fastmcp import FastMCP<br>import aiohttp<br># ...<br><br>mcp = FastMCP(&quot;serper_search&quot;)<br>SERPER_API_KEY = &quot;SERPER_API_KEY&quot; # Placeholder, real key from env<br><br>@mcp.tool()<br>async def search_web(query: str, limit: int = 5) -&gt; Dict[str, List]:<br>    &quot;&quot;&quot;<br>    Serper API kullanarak web araması yapar.<br>    Args:<br>        query: Arama sorgusu<br>        limit: Döndürülecek maksimum sonuç sayısı<br>    Returns:<br>        Arama sonuçlarını içeren bir sözlük<br>    &quot;&quot;&quot;<br>    # ... (API call logic using aiohttp to google.serper.dev/search) ...</pre><ul><li><strong>Benefit:</strong> Equips the agent with web search capabilities, allowing it to find current information, answer general knowledge questions, or research topics on demand.</li></ul><p><strong>Gmail MCP Server:</strong></p><ul><li><strong>Purpose:</strong> Allows the agent to interact with Gmail for sending and receiving emails.</li><li><strong>Implementation:</strong> Utilizes the @gongrzhe/server-gmail-autoauth-mcp package via npx, designed to simplify Gmail authentication, though initial setup or user consent might be needed.</li><li><strong>Benefit:</strong> Transforms the agent into a capable email assistant, able to manage communications, send notifications, or process information from emails.</li></ul><p>An example of a YAML file with MCP Server configurations is as follows.</p><pre>mcp:<br>    servers:<br>        fetch:<br>            command: &quot;uvx&quot;<br>            args: [&quot;mcp-server-fetch&quot;]<br>        filesystem:<br>            command: &quot;npx&quot;<br>            args: [&quot;-y&quot;, &quot;@modelcontextprotocol/server-filesystem&quot;, &quot;.&quot;]<br>        screenshot_capture:<br>            command: &quot;python&quot;<br>            args: [&quot;./created_mcp_servers/screenshot_capture.py&quot;]<br>        weather_api:<br>            command: &quot;python&quot;<br>            args: [&quot;./created_mcp_servers/weather_api.py&quot;]<br>        serper_search:<br>            command: &quot;python&quot;<br>            args: [&quot;./created_mcp_servers/serper_search.py&quot;]<br>        gmail:<br>            command: &quot;npx&quot;<br>            args: [&quot;@gongrzhe/server-gmail-autoauth-mcp&quot;]<br>        google-maps:<br>            command: &quot;npx&quot;<br>            args: [&quot;-y&quot;, &quot;@modelcontextprotocol/server-google-maps&quot;]<br>            env:<br>                GOOGLE_MAPS_API_KEY: &quot;AIza----------------------------------------------------&quot;<br>        slack:<br>            command: &quot;npx&quot;<br>            args: [<br>                &quot;-y&quot;,<br>                &quot;@modelcontextprotocol/server-slack&quot;<br>            ]<br>            env:<br>                SLACK_BOT_TOKEN: &quot;xoxb----------------------------------------------------&quot;<br>                SLACK_TEAM_ID: &quot;T-----------&quot;<br>                SLACK_CHANNEL_IDS: &quot;C------------, C------------,, C------------,&quot;<br>        sqlite:<br>            command: &quot;uv&quot;<br>            args: [<br>                &quot;--directory&quot;,<br>                &quot;./src/sqlite&quot;,<br>                &quot;run&quot;,<br>                &quot;mcp-server-sqlite&quot;,<br>                &quot;--db-path&quot;,<br>                &quot;test.db&quot;<br>            ]</pre><h3>The Agent Ecosystem: Specialized Roles for Comprehensive Capabilities</h3><p>This project doesn’t just rely on a single monolithic agent. Instead, FastAgent orchestrates a suite of specialized agents, each designed for specific tasks. This modular approach enhances maintainability and scalability. The core agents include:</p><ul><li><strong>route Agent:</strong> Acts as the central dispatcher. It receives incoming requests and intelligently directs them to the appropriate specialized agent based on the request&#39;s nature. It leverages all other specialized agents.</li></ul><pre># agent.py (Router Definition Excerpt)<br>from mcp_agent.core.fastagent import FastAgent<br># ...<br><br>fast = FastAgent(&quot;fast-agent-örneği&quot;)<br><br>@fast.router(<br>  name=&quot;route&quot;,<br>  agents=[&quot;chat_agent&quot;, &quot;screenshot_agent&quot;, &quot;weather_agent&quot;, &quot;search_agent&quot;, &quot;gmail_agent&quot;, &quot;maps_agent&quot;, &quot;slack_agent&quot;, &quot;sqlite_agent&quot;, &quot;fallback_agent&quot;],<br>  model=&quot;haiku&quot;,<br>  use_history=False,<br>  human_input=False<br>  )<br>async def route():<br>  pass</pre><ul><li><strong>orchestrate Agent:</strong> Manages the overall flow and coordination between different agents, initiating interactions usually by first invoking the route agent.</li></ul><pre># agent.py (Orchestrator Definition Excerpt)<br>@fast.orchestrator(<br>  name=&quot;orchestrate&quot;,<br>  agents=[&quot;route&quot;],<br>  model=&quot;haiku&quot;<br>)<br>async def orchestrate():<br>    pass</pre><ul><li><strong>chat_agent:</strong> Handles direct, conversational interactions with the user in Turkish, responding to greetings and general chat.</li></ul><pre># agent.py (Example Agent Definition - chat_agent)<br>@fast.agent(<br>    name=&quot;chat_agent&quot;,<br>    instruction=&quot;&quot;&quot;<br>    Sen kullanıcılarla doğrudan Türkçe sohbet eden bir ajansın.<br>    Selamlaşmalara ve günlük konuşmalara Türkçe yanıt verirsin.<br>    ... Her zaman Türkçe konuş ve yanıt ver. Asla İngilizce kullanma.<br>    &quot;&quot;&quot;,<br>    model=&quot;haiku&quot;,<br>    use_history=True,<br>    request_params=RequestParams(temperature=0.7),<br>    human_input=True<br>)<br>async def chat_agent():<br>    pass</pre><ul><li><strong>screenshot_agent:</strong> Dedicated to capturing screenshots when requested by the user, utilizing the screenshot_capture MCP server.</li></ul><pre># agent.py (Example Agent Definition - screenshot_agent)<br>@fast.agent(<br>    name=&quot;screenshot_agent&quot;,<br>    instruction=&quot;Ekran görüntüsü yakalayan yardımcı bir ajansın. Kullanıcı istediğinde onun ekranının görüntüsünü yakalayabilirsin.&quot;,<br>    servers=[&quot;screenshot_capture&quot;], # Links to the Screenshot Capture MCP Server<br>    model=&quot;haiku&quot;,<br>    use_history=True,<br>    request_params=RequestParams(temperature=0.7),<br>    human_input=True<br>)<br>async def screenshot_agent():<br>    pass</pre><ul><li><strong>weather_agent:</strong> Provides weather information for any city using the weather_api MCP server.</li></ul><pre># agent.py (Example Agent Definition - weather_agent)<br>@fast.agent(<br>    name=&quot;weather_agent&quot;,<br>    instruction=&quot;Hava durumu bilgisi sağlayan yardımcı bir ajansın. Kullanıcı istediğinde herhangi bir şehrin hava durumunu gösterebilirsin.&quot;,<br>    servers=[&quot;weather_api&quot;],<br>    model=&quot;haiku&quot;,<br>    use_history=True,<br>    request_params=RequestParams(temperature=0.7),<br>    human_input=True<br>)<br>async def weather_agent():<br>    pass</pre><ul><li><strong>search_agent:</strong> Performs internet searches via the serper_search MCP server based on user queries.</li></ul><pre># agent.py (Example Agent Definition - search_agent)<br>@fast.agent(<br>    name=&quot;search_agent&quot;,<br>    instruction=&quot;İnternet araması yapan yardımcı bir ajansın. Kullanıcı istediğinde web&#39;de arama yapabilir ve sonuçları gösterebilirsin.&quot;,<br>    servers=[&quot;serper_search&quot;],<br>    model=&quot;haiku&quot;,<br>    use_history=True,<br>    request_params=RequestParams(temperature=0.7),<br>    human_input=True<br>)<br>async def search_agent():<br>    pass</pre><ul><li><strong>gmail_agent:</strong> Manages Gmail interactions like sending and receiving emails, interfacing with the gmail MCP server.</li></ul><pre># agent.py (Example Agent Definition - gmail_agent)<br>@fast.agent(<br>    name=&quot;gmail_agent&quot;,<br>    instruction=&quot;E-posta gönderme ve alma gibi görevleri yerine getiren bir ajansın. Kullanıcının Gmail hesaplarıyla etkileşim kurabilirsin.&quot;,<br>    servers=[&quot;gmail&quot;],<br>    model=&quot;haiku&quot;,<br>    use_history=True,<br>    request_params=RequestParams(temperature=0.7),<br>    human_input=True<br>)<br>async def gmail_agent():<br>    pass</pre><ul><li><strong>maps_agent:</strong> Performs various map-related operations (geocoding, directions, etc.) through the google-maps MCP server.</li></ul><pre># agent.py (Example Agent Definition - maps_agent)<br>@fast.agent(<br>    name=&quot;maps_agent&quot;,<br>    instruction=&quot;Harita ile ilgili çeşitli işlemleri gerçekleştiren bir ajansın. Adresleri koordinatlara çevirebilir, koordinatları adreslere çevirebilir, yerleri arayabilir, yer detaylarını alabilir, mesafeleri hesaplayabilir, yükseklik bilgilerini alabilir ve yol tarifleri oluşturabilirsin.&quot;,<br>    servers=[&quot;google-maps&quot;],<br>    model=&quot;haiku&quot;,<br>    use_history=True,<br>    request_params=RequestParams(temperature=0.7),<br>    human_input=True<br>)<br>async def maps_agent():<br>    pass</pre><ul><li><strong>slack_agent:</strong> Interacts with Slack (listing channels, sending messages, etc.) via the slack MCP server, with all responses in Turkish.</li></ul><pre># agent.py (Example Agent Definition - slack_agent)<br>@fast.agent(<br>    name=&quot;slack_agent&quot;,<br>    instruction=&quot;&quot;&quot;Slack ile ilgili çeşitli işlemleri gerçekleştiren bir ajansın. <br>    Kanalları listeleyebilir, kanallara mesaj gönderebilir, mesajlara yanıt verebilir, mesajlara emoji ile tepki verebilir, kanal geçmişini alabilir, mesaj dizisi yanıtlarını alabilir, kullanıcıları listeleyebilir ve kullanıcı profillerini alabilirsin.<br>    Her zaman Türkçe yanıt ver.&quot;&quot;&quot;,<br>    servers=[&quot;slack&quot;],<br>    model=&quot;haiku&quot;,<br>    use_history=True,<br>    request_params=RequestParams(temperature=0.7),<br>    human_input=True<br>)<br>async def slack_agent():<br>    pass</pre><ul><li><strong>sqlite_agent:</strong> Interacts with the SQLite database using the sqlite MCP server, executing queries and providing responses in Turkish.</li></ul><pre># agent.py (Example Agent Definition - sqlite_agent)<br>@fast.agent(<br>    name=&quot;sqlite_agent&quot;,<br>    instruction=&quot;&quot;&quot;Sen bir SQLite veritabanı ile etkileşim kurabilen yardımcı bir ajansın.<br>    SQL sorguları çalıştırabilir, veritabanındaki tabloları listeleyebilir, tablo şemalarını getirebilir ve veritabanı üzerinde çeşitli işlemler yapabilirsin.<br>    Kullanıcının veritabanı ile ilgili isteklerini Türkçe olarak yanıtla.<br>    Örnek:<br>    Kullanıcı: Kullanıcılar tablosundaki tüm kayıtları göster.<br>    Sen: Elbette, kullanıcılar tablosundaki tüm kayıtları getiriyorum. [SONUÇLAR]<br>    Kullanıcı: Hangi tablolar var?<br>    Sen: Veritabanında şu tablolar mevcut: [TABLO LİSTESİ]<br>    Her zaman Türkçe yanıt ver.&quot;&quot;&quot;,<br>    servers=[&quot;sqlite&quot;],<br>    model=&quot;haiku&quot;,<br>    use_history=True,<br>    request_params=RequestParams(temperature=0.7),<br>    human_input=True<br>)<br>async def sqlite_agent():<br>    pass</pre><ul><li><strong>fallback_agent:</strong> Gracefully handles requests that don&#39;t fall within the capabilities of the other specialized agents. It politely informs the user in Turkish about the limitations and suggests alternative actions.</li></ul><pre># agent.py (Example Agent Definition - fallback_agent)<br>@fast.agent(<br>    name=&quot;fallback_agent&quot;,<br>    instruction=&quot;&quot;&quot;<br>    Sen yalnızca diğer ajanların (chat, screenshot, weather, search, gmail, maps, slack ve sqlite) işleyemediği istekleri alırsın.<br>    <br>    Bu tür durumlarda, kullanıcıya kibarca Türkçe olarak cevap ver ve şunları açıkla:<br>    1. İsteğinin mevcut yeteneklerimizin dışında olduğunu<br>    2. Nasıl yardımcı olabileceğini - örn. sohbet, ekran görüntüsü alma, hava durumu bilgisi, web araması, e-posta işlemleri, harita işlemleri, Slack işlemleri veya veritabanı (SQLite) işlemleri<br>    <br>    İstekleri reddettiğinde her zaman nazik ol ve alternatif önerilerde bulun.<br>    Her zaman Türkçe yanıt ver.<br>    &quot;&quot;&quot;,<br>    model=&quot;haiku&quot;,<br>    use_history=True,<br>    request_params=RequestParams(temperature=0.4),<br>    human_input=True<br>)<br>async def fallback_agent():<br>    pass</pre><p>These agents are defined in the agent.py file, using decorators like @fast.router, @fast.orchestrator, and @fast.agent to specify their roles, instructions, and associated MCP servers.</p><pre># agent.py (Router Definition Excerpt)<br>from mcp_agent.core.fastagent import FastAgent<br># ...<br><br>fast = FastAgent(&quot;fast-agent-örneği&quot;)<br><br>@fast.router(<br>  name=&quot;route&quot;,<br>  agents=[&quot;chat_agent&quot;, &quot;screenshot_agent&quot;, &quot;weather_agent&quot;, &quot;search_agent&quot;, &quot;gmail_agent&quot;, &quot;maps_agent&quot;, &quot;slack_agent&quot;, &quot;sqlite_agent&quot;, &quot;fallback_agent&quot;],<br>  model=&quot;haiku&quot;,<br>  use_history=False,<br>  human_input=False<br>  )<br>async def route():<br>  pass<br><br># ...<br><br># agent.py (Orchestrator Definition Excerpt)<br>@fast.orchestrator(<br>  name=&quot;orchestrate&quot;,<br>  agents=[&quot;route&quot;],<br>  model=&quot;haiku&quot;<br>)<br>async def orchestrate():<br>    pass</pre><h3>Illustrative Usage: Bringing the Agents to Life</h3><p>To understand the practical power of this setup, consider these example interactions:</p><ul><li><strong>Chat:</strong> “Merhaba, nasılsın?” (Hello, how are you?) would be handled by the chat_agent.</li><li><strong>Screenshot:</strong> “Ekranımın görüntüsünü alır mısın?” (Can you take a screenshot of my screen?) would trigger the screenshot_agent.</li><li><strong>Weather:</strong> “İstanbul için hava durumu nedir?” (What is the weather for Istanbul?) would be processed by the weather_agent.</li><li><strong>Search:</strong> “Türkiye’nin en yüksek dağı hangisidir?” (What is the highest mountain in Turkey?) would engage the search_agent.</li><li><strong>Gmail:</strong> “arkadas@example.com adresine &#39;Selam&#39; konulu bir e-posta gönder, içeriği &#39;Merhaba, nasılsın?&#39; olsun.&quot; (Send an email to arkadas@example.com with the subject &#39;Hi&#39; and body &#39;Hello, how are you?&#39;) demonstrates the gmail_agent&#39;s capability.</li><li><strong>Maps:</strong> “Ankara Kalesi’nden Anıtkabir’e yol tarifi oluştur.” (Create directions from Ankara Castle to Anıtkabir.) would be handled by the maps_agent.</li><li><strong>Slack:</strong> “#genel kanalına &#39;Herkese merhaba, günaydın!&#39; mesajını yolla.&quot; (Send the message &#39;Hello everyone, good morning!&#39; to the #general channel.) would use the slack_agent.</li><li><strong>SQLite:</strong> “urunler tablosundaki tüm verileri göster.&quot; (Show all data from the products table.) would be managed by the sqlite_agent.</li></ul><h3>The Advantages of This Architectural Approach</h3><p>Integrating FastAgent with a suite of MCP servers offers numerous benefits:</p><ul><li><strong>Standardized Communication:</strong> MCP provides a common language for agents and services, simplifying development and integration.</li><li><strong>Rich Interactivity &amp; Comprehensive Connectivity:</strong> Users experience a highly interactive environment with access to a wide array of services.</li><li><strong>Modularity and Scalability:</strong> The use of specialized agents and distinct MCP servers makes the system modular. New services can be added by creating or configuring new MCP servers, and new capabilities can be introduced by developing new agents without overhauling the entire system.</li><li><strong>Maintainability:</strong> Isolating functionalities into different agents and servers simplifies debugging and maintenance.</li><li><strong>Adherence to Best Practices:</strong> This architecture aligns with modern principles of agent-based system design.</li></ul><h3>Getting Started with Such a Project</h3><p>For those interested in building similar systems, the project outlined in the ogulcanakca-butler.txt file provides a clear blueprint. Key steps involve:</p><ol><li>Initialize a virtual environment (e.g., uv init).</li></ol><p>2. Activate it (source .venv/bin/activate or .venv\Scripts\activate).</p><p>3. Install dependencies from requirements.txt (e.g., uv pip install -r requirements.txt). This file lists packages like fast-agent-mcp, anthropic, openai, mss, aiohttp, etc.</p><p>4. Configure MCP servers and API keys.</p><p>5. Run the agent using uv run agent.py. The main function in agent.py handles the execution:</p><pre># agent.py (Main Execution Block)<br>async def main():<br>    async with fast.run() as agent_app:<br>        await agent_app.interactive(agent=&quot;orchestrate&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(main())</pre><h3>Conclusion: The Future is Connected</h3><p>The combination of FastAgent and Model Context Protocol servers represents a powerful paradigm for developing sophisticated AI agents. By standardizing communication and promoting a modular architecture, this approach enables the creation of AI systems that are not only highly capable and versatile but also scalable and maintainable. As AI continues to permeate various aspects of our digital lives, such frameworks will be crucial in building the next generation of intelligent applications.</p><p>Github Repository: <a href="https://github.com/ogulcanakca/butler">Link</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c914af326f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>