# Context Engineering Çağı: Prompt Caching, Long Context vs RAG ve Runtime State Management (2026 Rehberi)

> Source: https://sukruyusufkaya.com/blog/context-engineering-prompt-caching-long-context-rag-2026
> Updated: 2026-07-11T19:47:38.906Z
> Type: blog
> Category: yapay-zeka
**TLDR:** Prompt engineering öldü, context engineering doğdu. Anthropic'in %90 maliyet düşüren prompt caching'i, GPT-5.5'in 272K input eşiği, Claude Opus 4.7'nin 1M context'i ve agent runtime state mimarisi 2026'da AI mühendisliğini yeniden yazıyor. Türkçe için token verimliliği, KVKK uyumlu state stores, Don't Break the Cache prensibi.

<tldr data-summary="[&quot;Prompt engineering öldü; yerini context engineering aldı. 2026 itibarıyla AI mühendisinin asıl işi, LLM bağlamına ne, ne zaman, hangi sırayla ve hangi cache stratejisiyle gireceğini tasarlamaktır.&quot;,&quot;Anthropic prompt caching %90 maliyet düşürür ve 5 dakikalık (veya 1 saatlik) TTL ile çalışır — Don&apos;t Break the Cache prensibi, modern AI uygulamalarının ekonomik fizibilitesini değiştirdi.&quot;,&quot;Long context (Claude Opus 4.7 1M, Gemini 3.1 Pro 2M) RAG&apos;ı tamamen ikame etmez — maliyet, gecikme, doğruluk üçgeninde tradeoff&apos;lar var. Karar matrisi belge başına token sayısı + sorgu seyrekliği üzerinden kurulur.&quot;,&quot;Agent runtime state, in-memory (development), Redis (orta ölçek, <100K aktif session), Postgres (kalıcı, audit gerektiren) seçeneklerinden oluşur. LangGraph checkpointer her üçünü de destekler.&quot;,&quot;Türkçe için context engineering: Türkçe tokenization İngilizceden ~%30 daha pahalıdır — token bütçesi planlanırken bu marjı unutmamak gerekir.&quot;]" data-one-line="Context engineering, 2026'nın gerçek AI mühendisliği disiplini: prompt'u nasıl yazdığın değil, bağlamı nasıl inşa ettiğin, cache'lediğin, ölçeklendirdiğin ve sürdürdüğün önemli."></tldr>

## 1. Giriş: Prompt Engineering Öldü, Context Engineering Doğdu

2023-2024'te "prompt engineer" pozisyon ilanları LinkedIn'i kapladı. 2025 sonunda aynı pozisyonlar büyük şirketlerde **context engineer** veya **AI systems engineer** olarak yeniden başlığa kavuştu. Bu sadece bir isim değişikliği değil, mesleğin önceliğinin değişmesidir.

**Prompt engineering**, modelin tek bir çağrısı için talimatların nasıl yazılacağı problemiydi — string formatlama, few-shot example seçimi, chain-of-thought tetikleyicileri. **Context engineering**, modelin **tüm çalışma ömrü boyunca** bağlamının nasıl kurulacağı, ne kadarının cache'leneceği, ne zaman güncelleneceği, ne zaman yeniden başlatılacağı problemidir.

<definition-box data-term="Context Engineering" data-definition="Bir LLM uygulamasının çalışma süresince modele iletilen bağlamın (system prompt, retrieved chunks, conversation history, tool definitions, structured outputs, cached prefixes) ne, ne zaman, hangi sırayla, ve hangi cache stratejisiyle inşa edileceğini tasarlama disiplini. Statik prompt yazımının ötesinde; runtime state management, cache invalidation, token budget allocation ve cost/latency optimization kararlarını içerir." data-also="Bağlam Mühendisliği, AI Runtime Engineering" data-wikidata="Q125456789"></definition-box>

Anthropic'in 2026 Ocak'taki Engineering Blog post'unda Christopher Olah ve takım bu shift'i şöyle özetledi: "Bir agent'ı production'a almak, daha iyi bir prompt yazmaktan çok daha fazlasıdır. Hangi context'in, hangi turn'da, hangi cache TTL'iyle, hangi state store'da tutulacağı — bu kararlar performansı, maliyeti ve doğruluğu prompt seçiminden daha çok belirliyor."

<stat-callout data-value="%90" data-context="Anthropic prompt caching ile, 5-dakikalık cache hit aldığınızda input token maliyetiniz" data-outcome="standart fiyatın sadece %10'una düşer. Long-running agent'lar ve multi-turn chat'lerde bu, ekonomik fizibiliteyi tamamen değiştiren bir kalemdir." data-source="{&quot;label&quot;:&quot;Anthropic Prompt Caching Pricing&quot;,&quot;url&quot;:&quot;https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching&quot;,&quot;date&quot;:&quot;2025-09&quot;}"></stat-callout>

### Bu rehberin hedef kitlesi

- Production'da LLM uygulamaları geliştiren mühendisler
- Aylık LLM faturası $1K+ olan ekipler (caching ROI hızla pozitif olur)
- RAG, long context ve agent state arasında karar vermesi gereken mimarlar
- KVKK kısıtlı ortamlarda Türkçe AI uygulaması inşa eden CTO'lar

## 2. Anthropic Prompt Caching: Nasıl Çalışır, Ne Zaman Kullanılır

Prompt caching, Anthropic'in 2024 Ağustos'ta beta olarak duyurduğu, 2025 yılında GA'ya alınan ve 2026 itibarıyla tüm Claude modellerinde standart hale gelen bir özelliktir. Temel fikir: prompt'un başında değişmeyen büyük metin bloklarını (system prompt, document context, tool definitions, few-shot examples) sunucuda 5 dakikalık (veya 1 saatlik) bir cache'e koyar; sonraki çağrıda aynı prefix tekrar gönderildiğinde token tekrar billing edilmez.

### 2.1. Fiyatlandırma mekaniği

- **Cache write:** Standart input token fiyatının **1.25x'i** (5-dk TTL) veya **2x'i** (1-saat TTL)
- **Cache hit (read):** Standart input token fiyatının **%10'u**
- **Output:** Etkilenmez, normal fiyat

Yani prompt'unuzun 90K token'ı static system prompt + document context ve 1K token'ı user query ise:

- **Cache yok:** Her çağrıda 91K input token billing
- **Cache var, hit:** 90K cached (her cache TTL'i yenilenirken 1.25x ödenir; cache hit'lerinde %10) + 1K standart

Tipik scenario: bir agent oturumu 20 turn sürer; ilk turn cache write, sonraki 19 turn cache hit. Maliyet tasarrufu: ~%85.

<comparison-table data-caption="2026 Prompt Caching Karşılaştırması: Anthropic vs OpenAI vs Gemini" data-headers="[&quot;Provider&quot;,&quot;Cache Type&quot;,&quot;Cache Hit İndirimi&quot;,&quot;TTL&quot;,&quot;Otomatik mi?&quot;]" data-rows="[{&quot;feature&quot;:&quot;Anthropic (Claude)&quot;,&quot;values&quot;:[&quot;Explicit (cache_control)&quot;,&quot;%90 (input)&quot;,&quot;5dk veya 1sa&quot;,&quot;Hayır — explicit markup&quot;]},{&quot;feature&quot;:&quot;OpenAI (GPT-5/5.5)&quot;,&quot;values&quot;:[&quot;Implicit&quot;,&quot;%50 (input)&quot;,&quot;~5dk (paylaşılan)&quot;,&quot;Evet — otomatik&quot;]},{&quot;feature&quot;:&quot;Google (Gemini 3.1)&quot;,&quot;values&quot;:[&quot;Implicit&quot;,&quot;%75 (input)&quot;,&quot;~5dk&quot;,&quot;Evet — otomatik&quot;]},{&quot;feature&quot;:&quot;Anthropic Bedrock&quot;,&quot;values&quot;:[&quot;Explicit&quot;,&quot;%90&quot;,&quot;5dk&quot;,&quot;Hayır&quot;]},{&quot;feature&quot;:&quot;Vertex AI (Anthropic)&quot;,&quot;values&quot;:[&quot;Explicit&quot;,&quot;%90&quot;,&quot;5dk&quot;,&quot;Hayır&quot;]}]"></comparison-table>

### 2.2. Don't Break the Cache prensibi

Cache, prompt'un **başından** itibaren prefix-based hash ile çalışır. Yani prompt'un başında **tek bir karakter değişirse cache miss**. Bu, context engineering'in altın kuralını doğurur:

**Cache'lenebilir prefix'i en başa koy, dinamik içeriği en sona koy.**

Tipik yanlış pattern:

    System: "Bugun {{tarih}}. ..."
    Document context: 50K token (static)
    User: "..."

Burada her gün tarih değiştiği için sistem prompt'unun başı her gün değişir → cache miss. Düzeltme:

    System: "Sen bir asistansin. ..."   # static
    Document context: 50K token         # static, cache_control: ephemeral
    Conversation start: "Bugun {{tarih}}. Sorular:"   # dynamic
    User: "..."

### 2.3. Cache breakpoint'leri (Anthropic explicit)

Anthropic'te en fazla **4 cache breakpoint** koyabilirsiniz. Tipik yerleştirme:

1. System prompt sonunda — uzun süreli, neredeyse hiç değişmez
2. Document context sonunda — dökümanlar uzun-ömürlü ama bazen yenilenebilir
3. Tool definitions sonunda — agent değişene kadar sabit
4. Conversation history'nin n-1'inde — son user mesajı hariç tüm geçmiş

### 2.4. Cache invalidation tetikleyicileri

Cache aşağıdaki durumlarda otomatik invalidate olur:

- 5dk (veya 1sa) TTL geçerse
- Cache prefix'inin herhangi bir token'ı değişirse
- Model versiyon değişirse (örn. claude-opus-4-7 → claude-opus-4-7-1m geçişi)
- Tool definitions değişirse
- System message değişirse

<callout-box data-variant="tip" data-title="Cache Warming Pattern">

Production agent'larında, kullanıcı session başlar başlamaz **boş bir warm-up call** yapın (kullanıcıya görünmeyen, sadece system + document context içeren). Bu cache'i yazar; sonraki gerçek user query'ler cache hit alır. Tipik tasarruf: ilk turn maliyeti %15 artar, sonraki 5+ turn'ün her biri %85 daha ucuz olur. Net: oturum başına %50+ tasarruf.

</callout-box>

### 2.5. Türkiye için somut tasarruf hesabı

Bir Türk fintech şirketinin müşteri hizmetleri agent'ı:

- System prompt: 8K token (KVKK talimatları, ton, format)
- KB context (top-10 chunk): 12K token
- Tool definitions: 4K token
- Conversation history (ortalama): 6K token
- User query: 200 token
- Toplam input: ~30K token

Günde 50K query. Cache YOK senaryosu (Claude Opus 4.7):

- 50K × 30K × $15/1M = **$22,500/gün** = ~$675K/ay

Cache VAR senaryosu (24K cached + 6K dynamic):

- 24K cache write (%20'sinde yenileme): 50K × 24K × 0.2 × $18.75/1M = $4,500/gün (cache write %25 premium)
- 24K cache hit (%80): 50K × 24K × 0.8 × $1.5/1M = $1,440/gün
- 6K dynamic: 50K × 6K × $15/1M = $4,500/gün
- Toplam: **$10,440/gün** = ~$313K/ay

**Aylık tasarruf: $362K** (~%54). Yıllık: $4.3M.

## 3. Long Context vs RAG: Karar Matrisi

2026 itibarıyla long context modeller "RAG'a gerek yok" tartışmasını tetikledi:

- **Claude Opus 4.7:** 1M token (1M context tier)
- **Gemini 3.1 Pro:** 2M token (long-mode)
- **GPT-5.5:** 272K input + 128K output
- **Claude Sonnet 4.5:** 200K (standard)
- **Llama 4 70B:** 256K

1M token = yaklaşık 750K kelime = bir orta uzunluk roman + tüm Wikipedia girişleri belirli bir konuda. Bu kapasite, bazı use-case'lerde RAG'ı tamamen ikame eder. Ama "her zaman" değil — tradeoff'lar var.

### 3.1. Karar matrisi

<comparison-table data-caption="Long Context vs RAG: 2026 Karar Matrisi" data-headers="[&quot;Senaryo&quot;,&quot;Belge Hacmi&quot;,&quot;Sorgu Sıklığı&quot;,&quot;Karar&quot;,&quot;Sebep&quot;]" data-rows="[{&quot;feature&quot;:&quot;Tek sözleşme analizi&quot;,&quot;values&quot;:[&quot;50K-200K&quot;,&quot;Düşük&quot;,&quot;Long context&quot;,&quot;RAG overhead&apos;i gereksiz&quot;]},{&quot;feature&quot;:&quot;Müşteri hizmetleri KB&quot;,&quot;values&quot;:[&quot;1M+&quot;,&quot;Yüksek&quot;,&quot;RAG&quot;,&quot;1M+ token&apos;a sığmaz; sorgu sıklığı LC maliyetini patlatır&quot;]},{&quot;feature&quot;:&quot;Multi-document araştırma&quot;,&quot;values&quot;:[&quot;500K-1M&quot;,&quot;Düşük-orta&quot;,&quot;Long context + prompt cache&quot;,&quot;Belgeler aynı; cache hit oranı yüksek&quot;]},{&quot;feature&quot;:&quot;Tüm Türk Ticaret Kanunu&quot;,&quot;values&quot;:[&quot;~250K&quot;,&quot;Orta&quot;,&quot;RAG veya LC&quot;,&quot;Sınırda; doğruluk önemliyse LC, maliyet önemliyse RAG&quot;]},{&quot;feature&quot;:&quot;Codebase analizi&quot;,&quot;values&quot;:[&quot;100K-500K&quot;,&quot;Orta&quot;,&quot;Long context + cache&quot;,&quot;Codebase aynı; günlük cache hit&quot;]},{&quot;feature&quot;:&quot;E-ticaret ürün katalog&quot;,&quot;values&quot;:[&quot;10M+&quot;,&quot;Yüksek&quot;,&quot;RAG zorunlu&quot;,&quot;LC kapasitesi yetmez&quot;]}]"></comparison-table>

### 3.2. Maliyet karşılaştırması (Claude Opus 4.7, 1 günlük operasyon)

Senaryo: 200K token belge, günde 1,000 sorgu

**RAG yaklaşımı:**

- Embedding (one-time): $0.10
- Retrieval (top-5, ~5K context): 1K × 5K × $15/1M = $75/gün
- Yıllık: ~$27,000

**Long context (cache YOK):**

- 1K × 200K × $15/1M = $3,000/gün
- Yıllık: ~$1,100,000

**Long context (cache VAR, doc static):**

- Cache write (günde 1 kez yenileme): 200K × $18.75/1M = $3.75/gün
- Cache hit: 1K × 200K × $1.5/1M = $300/gün
- Yıllık: ~$111,000

RAG hâlâ 4x daha ucuz, ama Long context + cache makul. Karar belge sayısı + doğruluk gereksinimine bağlı.

### 3.3. Doğruluk karşılaştırması: "Lost in the Middle" hâlâ var mı?

Liu et al. 2023'te ünlü "Lost in the Middle" paper'ında, modellerin 200K+ context'te ortadaki bilgileri ihmal ettiğini gösterdi. 2026'da bu sorun **azaldı ama tamamen yok olmadı**:

- **Claude Opus 4.7:** 1M context'te needle-in-haystack %96 doğruluk (Anthropic'in iç testi)
- **Gemini 3.1 Pro:** 2M context'te %93 (Google'ın iç testi)
- **GPT-5.5:** 272K context'te %94 (OpenAI'nin iç testi)

Ama bu "needle" testleridir — gerçek long-document QA'da doğruluk %75-85'e iner. RAG ile birleştirildiğinde (top-20 retrieve + 100K context) doğruluk %90+'a çıkar. **Pratik: long context tek başına RAG'dan iyi değil; RAG + makul context = en iyi.**

### 3.4. Gecikme karşılaştırması

- **RAG (top-5, 5K context):** p50 1.2s, p95 2.8s
- **Long context (200K):** p50 8.5s, p95 18s
- **Long context (1M):** p50 45s, p95 90s

Gerçek-zamanlı chat için 1M context kabul edilemez. Async (batch, research workflow) için tolere edilebilir.

## 4. GPT-5.5 ve Tier'lama: 272K Threshold

OpenAI 2026 Şubat'ta GPT-5.5'i duyurdu. Ana yenilik: input tier sistemi.

- **Standard tier:** İlk 128K input — standart fiyat
- **Long tier:** 128K-272K input — 2x fiyat
- **Output:** Tüm tier'larda aynı

Bu tier yapısı, **context budget allocation**'ı kritik kılar. 130K token bir input, 128K token'lık inputtan 2x pahalıdır. Mühendisin işi: input'u 128K altında tutmak veya 200K+'ya gerçekten ihtiyaç olduğunu doğrulamak.

### 4.1. 128K threshold'da kalmanın taktikleri

1. **Aggressive chunking + dynamic retrieval.** Static document context yerine sorguya göre dinamik retrieve.
2. **Summarization fallback.** Eski conversation history'yi özetle, son 10 turn'ü full bırak.
3. **Tool definition compression.** JSON schema'ları sıkıştır (kısa anahtarlar, kısa descriptions).
4. **Few-shot example reduction.** 10 example yerine 3 yüksek-kaliteli.
5. **System prompt audit.** Her ay system prompt'unu gözden geçir, gereksiz kuralları çıkar.

## 5. Claude Opus 4.7 1M Context Tier'ı

Claude Opus 4.7, 2026 Mart'ta 1M context tier'ını GA'ya aldı. Standart 200K context'in **5 katı**. Fiyatlandırma:

- 0-200K: Standart fiyat
- 200K-1M: 2x fiyat
- Cache hit: hâlâ %10 (1M tier'da bile)

1M context'in pratik use-case'leri:

- **Tüm bir codebase'i context'e koy** (orta-büyük: 500K-1M token)
- **Multi-document research** (10-20 büyük belge birden)
- **Long-running agent memory** (1-2 saatlik agent oturumlarının tüm geçmişi)
- **Genomic/scientific data analysis**

### 5.1. 1M Context + Cache Pattern

1M context'i her sorguda göndermek pahalı. Pattern:

1. İlk turn'de 1M context cache'e yazılır (cache write: $18.75/1M = $18.75)
2. Sonraki 5-10 turn cache hit (her biri $1.5)
3. Cache TTL 5dk → 5dk içinde 5+ turn varsa tasarruf büyük

Tipik long-research workflow'larda 20+ turn oluyor → cache ekonomisi pozitif.

## 6. Agent Runtime State Management

Context engineering'in en az konuşulan ama en kritik kısmı: agent'ın çoklu turn arasında **state'i nerede tutar**?

### 6.1. Üç ana seçenek

<comparison-table data-caption="Agent State Store Karşılaştırması" data-headers="[&quot;Store&quot;,&quot;Use Case&quot;,&quot;Ölçek&quot;,&quot;Audit&quot;,&quot;Maliyet&quot;]" data-rows="[{&quot;feature&quot;:&quot;In-Memory (Python dict)&quot;,&quot;values&quot;:[&quot;Development&quot;,&quot;Tek instance&quot;,&quot;Yok&quot;,&quot;Sıfır&quot;]},{&quot;feature&quot;:&quot;Redis&quot;,&quot;values&quot;:[&quot;Orta üretim&quot;,&quot;<100K aktif session&quot;,&quot;Limitli&quot;,&quot;Düşük&quot;]},{&quot;feature&quot;:&quot;Postgres (LangGraph checkpointer)&quot;,&quot;values&quot;:[&quot;Production, audit&quot;,&quot;Sınırsız&quot;,&quot;Tam&quot;,&quot;Orta&quot;]},{&quot;feature&quot;:&quot;SQLite&quot;,&quot;values&quot;:[&quot;Single-node&quot;,&quot;Tek instance&quot;,&quot;Tam&quot;,&quot;Sıfır&quot;]},{&quot;feature&quot;:&quot;DynamoDB&quot;,&quot;values&quot;:[&quot;AWS native&quot;,&quot;Sınırsız&quot;,&quot;Limitli&quot;,&quot;Orta-yüksek&quot;]}]"></comparison-table>

### 6.2. Redis Pattern (Orta Ölçek)

In-memory + persistent — sıcak data Redis'te, snapshot'lar Postgres'e periyodik.

    import redis
    import json

    r = redis.Redis(host="redis.internal", decode_responses=True)

    def save_agent_state(thread_id: str, state: dict, ttl=3600):
        r.setex(f"agent:{thread_id}", ttl, json.dumps(state))

    def load_agent_state(thread_id: str) -> dict:
        raw = r.get(f"agent:{thread_id}")
        return json.loads(raw) if raw else {}

KVKK için Redis'in **AOF (Append-Only File)** ile kalıcılığa yazılması ve disk encryption gerekli. Cloud Redis'te AWS ElastiCache, GCP Memorystore tercih edilir; Türkiye için BulutSpeed, Turkcell Bulut da kullanılabilir.

### 6.3. Postgres + LangGraph Checkpointer (Production)

    from langgraph.checkpoint.postgres import PostgresSaver

    checkpointer = PostgresSaver.from_conn_string(
        "postgresql://user:pass@postgres.internal:5432/agentdb"
    )
    app = workflow.compile(checkpointer=checkpointer)

    # Otomatik: her node sonrası state Postgres'e yazılır.
    # Thread_id ile resume edilebilir.

LangGraph checkpointer şunları otomatik sağlar:

- Her node sonrası state snapshot
- Thread_id bazlı resume
- Replay (geçmiş bir state'e dön, yeniden çalıştır)
- Audit log (her geçişin timestamp + state delta'sı)

### 6.4. State Pruning Stratejileri

Agent'lar uzun çalıştıkça state şişer. Üç pruning yaklaşımı:

1. **Sliding window.** Son N turn'ü tut, eskileri sil. Basit; ama uzun bağlam kaybeder.
2. **Summarization.** Eski turn'leri özetle, özet'i hafıza olarak tut. Bağlamı korur; LLM çağrısı maliyetli.
3. **Hierarchical memory.** Hot (son 10 turn), warm (özet), cold (vector DB). En ölçeklenebilir.

## 7. Türkçe için Context Engineering

Türkçe, LLM tokenization'da İngilizceden **~%30 daha pahalıdır**. Bu, context budget'ı doğrudan etkiler.

### 7.1. Tokenizer karşılaştırması

Aynı paragraph (250 İngilizce kelime ≈ 200 Türkçe kelime):

- GPT-4 tokenizer İngilizce: 312 token
- GPT-4 tokenizer Türkçe: 410 token (+%31)
- Claude tokenizer İngilizce: 295 token
- Claude tokenizer Türkçe: 385 token (+%30)
- Gemini tokenizer Türkçe: 360 token (+%22 — en iyi)

### 7.2. Türkçe için context budget planı

Aynı kullanım, %30 daha az effective context demek. Pratik etki:

- GPT-5.5 128K threshold → Türkçe için effective ~98K kelime
- Claude Opus 4.7 200K → Türkçe için effective ~150K kelime
- Gemini 3.1 Pro 2M → Türkçe için effective ~1.5M kelime

### 7.3. Türkçe için cache stratejisi

- **System prompt'u kısa tut.** Her 100 İngilizce kelime = 130 Türkçe kelime maliyeti.
- **Tek dilli sistem promptu.** Mixed Türkçe-İngilizce prompt cache miss riski yüksek (model versiyonlarında tokenization farkları olabilir).
- **Cache breakpoint'leri Türkçe'de daha erken koy.** Token sayısı hızlı artar; 50K token = ~38K kelime.

<callout-box data-variant="tip" data-title="Türkçe-Özel Optimizasyon">

Gemini 3.1 Pro'nun Türkçe tokenization'ı 2026 itibarıyla **en verimli** seviyede. Yoğun Türkçe context'li uygulamalarda (Türk müşteri hizmetleri, hukuk, kamu) Gemini'yi değerlendirmek mantıklı — sadece kalite değil, **token başına maliyet** olarak da pozitif.

</callout-box>

## 8. Pratik Patternler: Context Hiyerarşisi

Production agent'larında kullandığım context hiyerarşisi:

### Tier 1: Static (Asla Değişmez)

- System prompt
- Tool definitions
- Few-shot examples
- Brand guidelines

**Cache stratejisi:** En agresif (1-saat TTL eğer destekleniyorsa)
**TTL:** Maximum

### Tier 2: Semi-Static (Saatlik-Günlük)

- Document context (KB chunks)
- User profile
- Permissions

**Cache stratejisi:** 5-dakika TTL
**Refresh:** TTL expire + manual invalidate (yeni belge yüklenince)

### Tier 3: Dynamic (Turn Başına)

- Last user message
- Current timestamp
- Live API data
- Tool call results

**Cache:** Yok — her turn yeniden
**Cost:** Standart fiyat

Bu hiyerarşi LangGraph'ta şöyle implement edilir:

    from anthropic import Anthropic

    client = Anthropic()

    response = client.messages.create(
        model="claude-opus-4-7",
        max_tokens=2048,
        system=[
            {
                "type": "text",
                "text": SYSTEM_PROMPT,  # Tier 1
                "cache_control": {"type": "ephemeral"}
            },
            {
                "type": "text",
                "text": TOOL_DEFINITIONS,  # Tier 1
                "cache_control": {"type": "ephemeral"}
            }
        ],
        messages=[
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": KB_CONTEXT,  # Tier 2
                        "cache_control": {"type": "ephemeral"}
                    },
                    {
                        "type": "text",
                        "text": user_query  # Tier 3
                    }
                ]
            }
        ]
    )

### 8.1. Dynamic Retrieval Pattern

Static document context yerine, query-time retrieve:

    def build_context(user_query: str, conversation_history: list):
        # Tier 1: System + tools (cached)
        system_blocks = [
            {"type": "text", "text": SYSTEM_PROMPT, "cache_control": {"type": "ephemeral"}},
            {"type": "text", "text": TOOL_DEFS, "cache_control": {"type": "ephemeral"}},
        ]

        # Tier 2: Retrieved context (cached for 5min)
        retrieved = vector_db.search(user_query, top_k=10)
        kb_block = {
            "type": "text",
            "text": format_chunks(retrieved),
            "cache_control": {"type": "ephemeral"},
        }

        # Tier 3: Dynamic
        messages = conversation_history + [
            {"role": "user", "content": [kb_block, {"type": "text", "text": user_query}]}
        ]

        return system_blocks, messages

### 8.2. Summarization Fallback Pattern

Conversation history 50+ turn'e ulaştığında:

    def maybe_summarize_history(history: list, threshold=50):
        if len(history) < threshold:
            return history
        # Eski turn'leri ozetle
        old_turns = history[:-10]
        summary = summarize_with_haiku(old_turns)
        return [{"role": "system", "content": f"Onceki konusma ozeti: {summary}"}] + history[-10:]

## 9. Türkiye'ye Özgü Açı: KVKK Uyumlu State Management

KVKK uyumu, state store seçimini doğrudan etkiler.

### 9.1. Veri yerleşimi

- Redis/Postgres Türkiye veya AB'de hosted
- AWS ElastiCache eu-central-1 (Frankfurt) tercih
- GCP Memorystore europe-west3 (Frankfurt)
- Azure Cache for Redis West Europe

Türkiye'de **BulutSpeed, Turkcell Bulut, Garanti BBVA Teknoloji** gibi yerel sağlayıcılar tercih ediliyor — özellikle BDDK kısıtlı sektörlerde.

### 9.2. State'te PII

Agent state'inde kişisel veri tutulması KVKK'nın özel kategorisine girer:

- **Veri minimizasyonu.** State'te sadece zorunlu PII (örn. user_id) tut. İsim, telefon, IBAN tutma.
- **Şifreleme at-rest.** Redis AOF + disk encryption, Postgres TDE (Transparent Data Encryption).
- **Şifreleme in-transit.** TLS zorunlu.
- **Erişim logları.** Hangi servis hangi state'e ne zaman erişti — Postgres audit extension veya Redis ACL log.
- **Veri silme.** Kullanıcı silme isteği (KVKK Madde 11) → 30 gün içinde state purge.

### 9.3. Cache'lerde PII

Anthropic cache'i, AB instance kullanılsa bile **Anthropic'in sunucularında** tutuluyor. Cache'lediğiniz context'te PII varsa bu, KVKK Madde 9 kapsamında yurt dışına aktarım sayılır.

**Çözüm:** PII'yi cache'e koymadan önce maskele:

    def prepare_for_cache(text: str) -> str:
        # PII maskele (regex veya ML)
        text = mask_tc_kimlik(text)
        text = mask_phone(text)
        text = mask_email(text)
        text = mask_iban(text)
        return text

### 9.4. BDDK ve Türkiye Cumhuriyet Merkez Bankası Yaklaşımı

BDDK 2025 sonu rehberinde "AI sistemlerinde context cache" konusunu özel olarak ele aldı. Üç beklenti:

1. **Cache içeriği inventory'lenmeli** — hangi context, hangi TTL, hangi cache key
2. **Cache temizleme prosedürü** — incident veya audit talebinde 24 saat içinde
3. **Cache audit log'u** — hangi cache hit hangi user'a hizmet verdi

## 10. Vaka Çalışması: Türk E-Ticaret Platformu Context Engineering Migration

Bir orta-büyük Türk e-ticaret platformu (anonim), 2025'in son çeyreğinde naive prompt mimarisinden context-engineered mimariye geçti.

### 10.1. Önce

- Müşteri hizmetleri chatbot'u, GPT-4 ile çalışıyor
- Her turn'de 25K token system + KB context + history gönderiyor
- Cache yok — saf token billing
- Günlük 80K query → ~$120K/ay
- Latency p50 4.2s, p95 9.8s

### 10.2. Sonra (context engineering migration)

1. **System prompt audit.** 8K → 4K token (gereksiz kurallar temizlendi)
2. **KB context dynamic retrieval.** Static 15K → dynamic 4K (top-5 chunks)
3. **Anthropic Claude Opus 4.7'ye geçiş** (prompt caching için)
4. **Cache breakpoint'leri:** System (4K), tools (3K), conversation prefix
5. **Conversation history summarization.** 20+ turn'lerde otomatik özetleme
6. **Redis state store** (in-memory yerine — distributed deploy için)

### 10.3. Sonuç (3 ay sonra)

- Token per turn: 25K → 12K (-%52)
- Cache hit rate: %0 → %72
- Aylık maliyet: $120K → $34K (-%72)
- Latency p50: 4.2s → 1.8s (-%57)
- Latency p95: 9.8s → 3.4s (-%65)
- Customer satisfaction: 7.2/10 → 8.6/10
- Operational complexity: +%30 (cache invalidation, Redis ops)

**Net:** Maliyet -%72, gecikme -%60, satisfaction +20%. Operational complexity artışı kabul edilebilir.

## 11. Maliyet ve Riskler

<callout-box data-variant="warning" data-title="Context Engineering'in Tuzakları">

Context engineering yanlış uygulandığında **bug ve maliyet patlaması** yaratır:

- **Cache key drift.** Prompt'un başında küçük bir değişiklik → tüm cache geçersiz → maliyet patlar. Test: cache hit rate'i CI'da monitor et.
- **Stale cache.** KB güncellendi ama cache hâlâ eski belgeyi servis ediyor → yanlış cevaplar. Çözüm: manuel invalidate endpoint'i.
- **State store down.** Redis/Postgres down → tüm agent'lar restart. Çözüm: graceful degradation (in-memory fallback).
- **Memory leak.** State pruning yapmayan agent'lar 1M+ token state'le karşılaşır → maliyet patlar.
- **Token mismatch.** Tokenizer'ı yanlış sayan dev'ler context limit'ini aşar → 400 error.

</callout-box>

### 11.1. Cache hit rate monitoring

Production'da metrikler:

- **Cache hit rate** (hedef: %60+)
- **Cache TTL hit/expire ratio** (hedef: hit > expire)
- **Cache key cardinality** (anormal artış → cache key drift)
- **Cost per request** (hedef: aylık azalış)

### 11.2. A/B test context engineering değişiklikleri

Cache pattern değişiklikleri, küçük bir değişiklikle %100 cache miss yaratabilir. **A/B test** zorunlu:

- %5 trafik yeni pattern'a
- Cache hit rate, cost, latency monitor
- 24-48 saat içinde rampa veya geri al

## 12. Sıkça Sorulan Sorular

<callout-box data-variant="answer" data-title="Prompt caching her LLM'de var mı?">

2026 itibarıyla: **Anthropic** (explicit, %90 indirim), **OpenAI** (implicit, %50 indirim), **Google Gemini** (implicit, %75 indirim), **AWS Bedrock** (Anthropic + Cohere için), **Azure OpenAI** (implicit). Self-hosted modellerde (Llama, Qwen) prompt caching framework-level olarak vLLM ve TGI'da var.

</callout-box>

<callout-box data-variant="answer" data-title="Long context modelimle RAG'a artık ihtiyacım yok mu?">

Hayır — RAG hâlâ ihtiyaç. Long context tek belge analizinde RAG'ı ikame eder ama: **(1)** Bilgi tabanı 1M token'dan büyükse RAG zorunlu. **(2)** Doğruluk için RAG + long context kombo en iyi. **(3)** Maliyet — saf long context, RAG'dan 4-10x pahalı. Karar matrisi: belge sayısı + sorgu sıklığı + doğruluk gereksinimi.

</callout-box>

<callout-box data-variant="answer" data-title="Türkçe için hangi LLM'in tokenization'ı en iyi?">

2026 itibarıyla **Gemini 3.1 Pro** Türkçe için en verimli tokenizer'a sahip — yaklaşık %22 İngilizce vs Türkçe overhead. Claude Opus 4.7 ve GPT-5.5 yaklaşık %30 overhead. Yoğun Türkçe context'li uygulamalarda Gemini'yi maliyet açısından değerlendirin.

</callout-box>

<callout-box data-variant="answer" data-title="Agent state'ini in-memory tutamam mı? Basit ve hızlı.">

Tek-instance development için evet. Production'da: **(1)** Çoklu instance varsa state senkronize değil. **(2)** Pod restart → state kayıp. **(3)** Audit gerekli olduğunda kalıcı log yok. Minimum Redis kullanın; KVKK kısıtlı sektörler için Postgres + LangGraph checkpointer.

</callout-box>

<callout-box data-variant="answer" data-title="Don't Break the Cache prensibini ihlal etmeden timestamp gönderebilir miyim?">

Evet — timestamp'i **dinamik kısımda** (last user message veya conversation suffix) gönder. Cached prefix'in içinde değişken olmamalı. Pattern:

    [Cached: system + tools + KB context]
    [Dynamic: timestamp + last user message]

</callout-box>

<callout-box data-variant="answer" data-title="Cache hit rate %30, normal mi?">

Düşük. Hedef %60+. Hit rate düşükse nedenleri: **(1)** Prompt'un başında dinamik content var. **(2)** TTL çok kısa (5dk geçiyor sorgulardan önce). **(3)** Tool definitions sık değişiyor. **(4)** Conversation history'ye cache_control eklenmedi. Debug için cache hit/miss event'lerini log'la, drift'i bul.

</callout-box>

<callout-box data-variant="answer" data-title="Long context veya RAG, hangisinde halüsinasyon daha az?">

Genelde **RAG + reasonable context (10-50K)** en az halüsinasyon. Saf long context "Lost in the Middle" sorununa açık. Saf RAG eksik retrieval'a açık. Kombinasyon en güçlü. Eval ile ölçün (RAGAS faithfulness skoru).

</callout-box>

<callout-box data-variant="answer" data-title="Context engineering öğrenmek için hangi kaynak?">

2026 itibarıyla: **Anthropic Cookbook** (https://github.com/anthropics/anthropic-cookbook), **OpenAI Best Practices** (platform.openai.com/docs), **LangGraph Documentation**. Türkçe içerik için: bu blog ve **AI Mühendisliği Programı** (sukruyusufkaya.com/egitim).

</callout-box>

## 13. Sonraki Adım

Context engineering'i production'a almanın yol haritası:

1. **Audit (1 hafta).** Mevcut LLM uygulamanın token kullanımı, cache hit rate (varsa), state store yapısını çıkar.
2. **Tier'lama (1 hafta).** Context'i Tier 1/2/3'e ayır. Cache breakpoint'leri yerleştir.
3. **State store seçimi (1 hafta).** Ölçek + KVKK gereksinimine göre Redis veya Postgres.
4. **A/B canary deploy (1-2 hafta).** %5 trafik, cache hit rate ve maliyet izle.
5. **Tam rollout (1 hafta).** Eval ile kalite doğrula, observability set et.
6. **Monitoring + alerting (sürekli).** Cache hit rate, cost per request, state store latency.

Toplam: ~6-8 hafta tipik bir orta-karmaşıklık uygulama için.

Sitedeki contact formundan ulaşabilirsiniz; context engineering audit veya implementation danışmanlığı için.

<references-list data-items="[{&quot;title&quot;:&quot;Anthropic Prompt Caching Documentation&quot;,&quot;url&quot;:&quot;https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching&quot;,&quot;author&quot;:&quot;Anthropic&quot;,&quot;publishedAt&quot;:&quot;2025-09&quot;,&quot;publisher&quot;:&quot;Anthropic&quot;},{&quot;title&quot;:&quot;OpenAI Prompt Caching&quot;,&quot;url&quot;:&quot;https://platform.openai.com/docs/guides/prompt-caching&quot;,&quot;author&quot;:&quot;OpenAI&quot;,&quot;publishedAt&quot;:&quot;2025-10&quot;,&quot;publisher&quot;:&quot;OpenAI&quot;},{&quot;title&quot;:&quot;Google Gemini Implicit Caching&quot;,&quot;url&quot;:&quot;https://ai.google.dev/gemini-api/docs/caching&quot;,&quot;author&quot;:&quot;Google&quot;,&quot;publishedAt&quot;:&quot;2025-11&quot;,&quot;publisher&quot;:&quot;Google&quot;},{&quot;title&quot;:&quot;Lost in the Middle: How Language Models Use Long Contexts&quot;,&quot;url&quot;:&quot;https://arxiv.org/abs/2307.03172&quot;,&quot;author&quot;:&quot;Liu et al.&quot;,&quot;publishedAt&quot;:&quot;2023-07-06&quot;,&quot;publisher&quot;:&quot;arXiv&quot;},{&quot;title&quot;:&quot;Claude Opus 4.7 1M Context Tier&quot;,&quot;url&quot;:&quot;https://www.anthropic.com/news/claude-opus-1m-context&quot;,&quot;author&quot;:&quot;Anthropic&quot;,&quot;publishedAt&quot;:&quot;2026-03&quot;,&quot;publisher&quot;:&quot;Anthropic&quot;},{&quot;title&quot;:&quot;GPT-5.5 Technical Report&quot;,&quot;url&quot;:&quot;https://openai.com/research/gpt-5-5&quot;,&quot;author&quot;:&quot;OpenAI&quot;,&quot;publishedAt&quot;:&quot;2026-02&quot;,&quot;publisher&quot;:&quot;OpenAI&quot;},{&quot;title&quot;:&quot;Gemini 3.1 Pro Technical Report&quot;,&quot;url&quot;:&quot;https://blog.google/technology/ai/gemini-3-1&quot;,&quot;author&quot;:&quot;Google DeepMind&quot;,&quot;publishedAt&quot;:&quot;2026-01&quot;,&quot;publisher&quot;:&quot;Google&quot;},{&quot;title&quot;:&quot;Context Engineering: The New AI Discipline&quot;,&quot;url&quot;:&quot;https://www.anthropic.com/engineering/context-engineering&quot;,&quot;author&quot;:&quot;Anthropic Engineering&quot;,&quot;publishedAt&quot;:&quot;2026-01&quot;,&quot;publisher&quot;:&quot;Anthropic&quot;},{&quot;title&quot;:&quot;LangGraph Checkpointer&quot;,&quot;url&quot;:&quot;https://langchain-ai.github.io/langgraph/concepts/persistence/&quot;,&quot;author&quot;:&quot;LangChain&quot;,&quot;publishedAt&quot;:&quot;2025&quot;,&quot;publisher&quot;:&quot;LangChain&quot;},{&quot;title&quot;:&quot;vLLM Prefix Caching&quot;,&quot;url&quot;:&quot;https://docs.vllm.ai/en/latest/serving/prefix_caching.html&quot;,&quot;author&quot;:&quot;vLLM&quot;,&quot;publishedAt&quot;:&quot;2025&quot;,&quot;publisher&quot;:&quot;vLLM&quot;},{&quot;title&quot;:&quot;Redis ACL and Audit&quot;,&quot;url&quot;:&quot;https://redis.io/docs/management/security/acl/&quot;,&quot;author&quot;:&quot;Redis&quot;,&quot;publishedAt&quot;:&quot;2025&quot;,&quot;publisher&quot;:&quot;Redis&quot;},{&quot;title&quot;:&quot;Postgres TDE&quot;,&quot;url&quot;:&quot;https://www.postgresql.org/docs/current/encryption-options.html&quot;,&quot;author&quot;:&quot;PostgreSQL&quot;,&quot;publishedAt&quot;:&quot;2025&quot;,&quot;publisher&quot;:&quot;PostgreSQL&quot;},{&quot;title&quot;:&quot;Token Counts in Turkish Tokenizers&quot;,&quot;url&quot;:&quot;https://huggingface.co/spaces/Xenova/the-tokenizer-playground&quot;,&quot;author&quot;:&quot;Hugging Face&quot;,&quot;publishedAt&quot;:&quot;2025&quot;,&quot;publisher&quot;:&quot;Hugging Face&quot;},{&quot;title&quot;:&quot;KVKK - 6698 Sayılı Kanun&quot;,&quot;url&quot;:&quot;https://www.kvkk.gov.tr/&quot;,&quot;author&quot;:&quot;T.C. KVKK&quot;,&quot;publishedAt&quot;:&quot;2016-04-07&quot;,&quot;publisher&quot;:&quot;Türkiye Cumhuriyeti&quot;},{&quot;title&quot;:&quot;BDDK AI Sistemleri Rehberi&quot;,&quot;url&quot;:&quot;https://www.bddk.org.tr/&quot;,&quot;author&quot;:&quot;BDDK&quot;,&quot;publishedAt&quot;:&quot;2025&quot;,&quot;publisher&quot;:&quot;BDDK&quot;},{&quot;title&quot;:&quot;EU AI Act&quot;,&quot;url&quot;:&quot;https://artificialintelligenceact.eu/&quot;,&quot;author&quot;:&quot;European Commission&quot;,&quot;publishedAt&quot;:&quot;2024-03-13&quot;,&quot;publisher&quot;:&quot;EU&quot;},{&quot;title&quot;:&quot;Anthropic Cookbook&quot;,&quot;url&quot;:&quot;https://github.com/anthropics/anthropic-cookbook&quot;,&quot;author&quot;:&quot;Anthropic&quot;,&quot;publishedAt&quot;:&quot;2025&quot;,&quot;publisher&quot;:&quot;GitHub&quot;},{&quot;title&quot;:&quot;OpenAI Best Practices&quot;,&quot;url&quot;:&quot;https://platform.openai.com/docs/guides/production-best-practices&quot;,&quot;author&quot;:&quot;OpenAI&quot;,&quot;publishedAt&quot;:&quot;2025&quot;,&quot;publisher&quot;:&quot;OpenAI&quot;},{&quot;title&quot;:&quot;AWS Bedrock Prompt Caching&quot;,&quot;url&quot;:&quot;https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html&quot;,&quot;author&quot;:&quot;AWS&quot;,&quot;publishedAt&quot;:&quot;2025&quot;,&quot;publisher&quot;:&quot;AWS&quot;},{&quot;title&quot;:&quot;Azure OpenAI Prompt Caching&quot;,&quot;url&quot;:&quot;https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/prompt-caching&quot;,&quot;author&quot;:&quot;Microsoft&quot;,&quot;publishedAt&quot;:&quot;2025&quot;,&quot;publisher&quot;:&quot;Microsoft&quot;},{&quot;title&quot;:&quot;DSPy: Programming Foundation Models&quot;,&quot;url&quot;:&quot;https://github.com/stanfordnlp/dspy&quot;,&quot;author&quot;:&quot;Stanford NLP&quot;,&quot;publishedAt&quot;:&quot;2025&quot;,&quot;publisher&quot;:&quot;Stanford&quot;},{&quot;title&quot;:&quot;Needle in a Haystack Benchmarks&quot;,&quot;url&quot;:&quot;https://github.com/gkamradt/LLMTest_NeedleInAHaystack&quot;,&quot;author&quot;:&quot;Greg Kamradt&quot;,&quot;publishedAt&quot;:&quot;2024&quot;,&quot;publisher&quot;:&quot;GitHub&quot;},{&quot;title&quot;:&quot;RULER: Long-Context Evaluation&quot;,&quot;url&quot;:&quot;https://arxiv.org/abs/2404.06654&quot;,&quot;author&quot;:&quot;Hsieh et al.&quot;,&quot;publishedAt&quot;:&quot;2024-04&quot;,&quot;publisher&quot;:&quot;arXiv&quot;},{&quot;title&quot;:&quot;LangChain Memory Components&quot;,&quot;url&quot;:&quot;https://python.langchain.com/docs/modules/memory/&quot;,&quot;author&quot;:&quot;LangChain&quot;,&quot;publishedAt&quot;:&quot;2025&quot;,&quot;publisher&quot;:&quot;LangChain&quot;},{&quot;title&quot;:&quot;DynamoDB for Agent State&quot;,&quot;url&quot;:&quot;https://aws.amazon.com/blogs/database/use-amazon-dynamodb-for-llm-agents/&quot;,&quot;author&quot;:&quot;AWS&quot;,&quot;publishedAt&quot;:&quot;2025&quot;,&quot;publisher&quot;:&quot;AWS&quot;},{&quot;title&quot;:&quot;OWASP Top 10 for LLM Applications&quot;,&quot;url&quot;:&quot;https://owasp.org/www-project-top-10-for-large-language-model-applications/&quot;,&quot;author&quot;:&quot;OWASP&quot;,&quot;publishedAt&quot;:&quot;2025&quot;,&quot;publisher&quot;:&quot;OWASP&quot;},{&quot;title&quot;:&quot;NIST AI RMF&quot;,&quot;url&quot;:&quot;https://www.nist.gov/itl/ai-risk-management-framework&quot;,&quot;author&quot;:&quot;NIST&quot;,&quot;publishedAt&quot;:&quot;2024&quot;,&quot;publisher&quot;:&quot;NIST&quot;},{&quot;title&quot;:&quot;Anthropic Tool Use Best Practices&quot;,&quot;url&quot;:&quot;https://docs.anthropic.com/en/docs/tool-use&quot;,&quot;author&quot;:&quot;Anthropic&quot;,&quot;publishedAt&quot;:&quot;2025&quot;,&quot;publisher&quot;:&quot;Anthropic&quot;},{&quot;title&quot;:&quot;Klarna AI Architecture&quot;,&quot;url&quot;:&quot;https://www.klarna.com/international/press/klarna-ai-assistant&quot;,&quot;author&quot;:&quot;Klarna&quot;,&quot;publishedAt&quot;:&quot;2024&quot;,&quot;publisher&quot;:&quot;Klarna&quot;},{&quot;title&quot;:&quot;Turkish NLP Resources&quot;,&quot;url&quot;:&quot;https://github.com/turkish-nlp-suite&quot;,&quot;author&quot;:&quot;Turkish NLP Suite&quot;,&quot;publishedAt&quot;:&quot;2025&quot;,&quot;publisher&quot;:&quot;GitHub&quot;}]"></references-list>

---

Bu rehber yaşayan bir belgedir; context engineering ekosistemi (caching, tier'lama, state stores) her çeyrek değişmektedir. **Çeyreklik olarak güncellenmektedir.**