Kv Cache Prefix Optimizer logo

Kv Cache Prefix Optimizer

Community
roedyrustam
kv-cache-prefix-optimizer

Deterministic prompt prefix engineering & KV-cache hit optimization / Rekayasa prefix prompt deterministik & optimasi cache KV.

Overview

Publisherroedyrustam
Repositoryvibes-plug
Skill namekv-cache-prefix-optimizer
Stars
117
Forks
27
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by roedyrustam on GitHub. Read the source before you install it.

Installation

Install the Kv Cache Prefix Optimizer AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/roedyrustam/vibes-plug/tree/main/skills/kv-cache-prefix-optimizer
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/roedyrustam/vibes-plug.git /tmp/vibes-plug
mkdir -p .claude/skills
cp -r /tmp/vibes-plug/skills/kv-cache-prefix-optimizer .claude/skills/kv-cache-prefix-optimizer
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Kv Cache Prefix Optimizer in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Kv Cache Prefix Optimizer on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Kv Cache Prefix Optimizer is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

kv-cache-prefix-optimizer — vibes-plug Skill

English | Bahasa Indonesia


English

Orchestration & Integration

  • Upstream & Orchestration: zero-to-prod-orchestrator (Phase 4 AI agent integration), brainstorming, session-memory-manager.
  • Frontier LLM & Model Caching: frontier-ai-models-expert (Gemini 4 Argon/Pro, Claude 5.5 Sonnet/Opus, Claude Fable 5.1, GPT-5.6 Sol, Grok 4.7 caching specs), gemini-agent-booster (Google 2M+ native context caching), vercel-ai-sdk-expert (provider cache controls).
  • FinOps & Adaptive Execution: llm-finops-router (cost calculation & cache routing), adaptive-model-cascade (cascade tier prefixing), thinking-budget-orchestrator (prefix pinning with thinking tokens).
  • Prompt Engineering & Context Windows: ai-prompt-engineering-expert (prompt canonicalization), context-window-engineer (large context sliding windows).

Description

Production guide for engineering deterministic prompt prefixes, stabilizing KV-cache boundaries, and optimizing context reuse across late-2026 frontier models (Google Gemini 4 Argon / Pro context caching, Anthropic Claude 5.5 / 5.1 prompt caching, OpenAI GPT-5.6 Sol prefix caching, and xAI Grok 4.7). Delivers architectures that guarantee 90%+ cache hit rates through canonical tool definition sorting, stable JSON serialization, and dynamic context partitioning.

Trigger Conditions

Activate this skill when:

  • Operating large-context agents (>100k tokens) where recurring prompt costs dominate operational budgets.
  • Experiencing high Time-to-First-Token (TTFT) latencies in interactive chat or agentic coding loops.
  • Configuring model caching primitives (cache_control: { type: 'ephemeral' } or Gemini explicit cache tokens).
  • Architecting system instructions, tool schemas, and workspace context maps for multi-turn sessions.

Core Concepts & Patterns

1. The Anatomy of a High-Cache Prompt

Modern frontier models utilize prefix-matching algorithms. Even a single changed byte (such as a timestamp, random ID, or altered tool order) invalidates all subsequent cached tokens:

[STATIC PREFIX: CACHE PINNED (90%+ HIT RATE)]
  ├── System Directives & Behavioral Guardrails (Immutable)
  ├── 171-Skill Ecosystem Registry (Canonical Alphabetical Order)
  ├── Tool Definitions (Strictly Sorted Keys & Parameters)
  └── Workspace Schema & Architecture Map (Immutable per Session)
------------------------ [CACHE BOUNDARY PIN] ------------------------
[DYNAMIC SUFFIX: VOLATILE PER TURN]
  ├── Ephemeral Turn Timestamp & User Message
  └── Real-Time Tool Execution Results
2. Deterministic Prompt & Cache Pinning (TypeScript Implementation)
typescript
export interface ToolDefinition {
  name: string;
  description: string;
  parameters: Record<string, unknown>;
}

export function serializeCanonicalJson(obj: unknown): string {
  if (obj === null || typeof obj !== 'object') {
    return JSON.stringify(obj);
  }
  if (Array.isArray(obj)) {
    return `[${obj.map((item) => serializeCanonicalJson(item)).join(',')}]`;
  }
  const sortedKeys = Object.keys(obj as Record<string, unknown>).sort();
  const entries = sortedKeys.map(
    (key) => `${JSON.stringify(key)}:${serializeCanonicalJson((obj as Record<string, unknown>)[key])}`
  );
  return `{${entries.join(',')}}`;
}

export function sortToolsCanonically(tools: ToolDefinition[]): ToolDefinition[] {
  return [...tools].sort((a, b) => a.name.localeCompare(b.name));
}

export interface PromptPayload {
  systemPrompt: string;
  cachedContextBlock: {
    type: 'text';
    text: string;
    cache_control: { type: 'ephemeral' };
  };
  messages: Array<{ role: 'user' | 'assistant'; content: string }>;
}

export function constructCacheOptimizedPayload(
  systemDirectives: string,
  staticWorkspaceContext: string,
  tools: ToolDefinition[],
  userTurns: Array<{ role: 'user' | 'assistant'; content: string }>
): PromptPayload {
  const sortedTools = sortToolsCanonically(tools);
  const canonicalToolSpecs = serializeCanonicalJson(sortedTools);

  const staticPinnedBlock = [
    '=== IMMUTABLE SYSTEM CONTEXT ===',
    systemDirectives,
    '=== CANONICAL TOOL REGISTRY ===',
    canonicalToolSpecs,
    '=== PROJECT ARCHITECTURAL MAP ===',
    staticWorkspaceContext
  ].join('\n\n');

  return {
    systemPrompt: 'You are an advanced sovereign AI coding agent operating under strict anti-slop guidelines.',
    cachedContextBlock: {
      type: 'text',
      text: staticPinnedBlock,
      cache_control: { type: 'ephemeral' }
    },
    messages: userTurns
  };
}
3. Cache Performance & Telemetry Targets
MetricUnoptimized BaselineKV-Cache Optimized TargetImprovement Factor
Cache Hit Ratio0% - 20%90% - 98%4.5x - 5x higher
Time-to-First-Token (TTFT)3,200ms - 5,500ms250ms - 450ms~10x faster response
Prompt Token Cost100% full rate20% - 25% discounted rate75% - 80% cost reduction

Best Practices

  1. Never Insert Timestamps in System Prompts: Place dates or timestamps exclusively in the final volatile user message, never in the static system prompt.
  2. Sort Tool Definitions Alphabetically: Always sort tool names and their JSON schema parameter keys canonically before sending requests.
  3. Partition Dynamic Context to the Tail: Ensure all large documentation and code context maps appear before volatile conversation history.
  4. Monitor Cache Read Discrepancies: Log usage.prompt_tokens_details.cached_tokens in application telemetry to catch accidental prefix cache busts immediately.
  5. Cache Prefix Portability & Availability Fallback: Preserve identical system prefix structures across model fallback pairs (Gemini 4 Argon/Pro <-> Gemini 3.8 Flash, Claude Opus 5.5 <-> Claude Opus 4.6) so that if an availability switch occurs, subsequent turns immediately re-warm the KV-cache without format discrepancies.

Common Pitfalls to Avoid

Anti-PatternOperational ConsequenceEngineering Remedy
Dynamic session IDs embedded in the system prompt100% cache invalidation on every user sessionRelocate session IDs to application state headers
Randomized order of tools from Object.values(tools)Non-deterministic JSON payload busts KV cacheSort tools alphabetically by name and schema keys
Modifying instruction wording midway through conversationRe-reads entire 100k+ token context at full priceKeep static prompt templates strictly versioned and immutable

Gemini 4 Argon / Flash Fallback Prefix Cache Manager (TypeScript)
typescript
export interface PrefixCacheDescriptor {
  prefixHash: string;
  modelId: 'gemini-4-argon-medium' | 'gemini-3.8-flash';
  estimatedTokens: number;
}

export function computePrefixDescriptor(
  staticPrefixText: string,
  isGemini4Available: boolean
): PrefixCacheDescriptor {
  let hash = 2166136261;
  for (let i = 0; i < staticPrefixText.length; i++) {
    hash ^= staticPrefixText.charCodeAt(i);
    hash = Math.imul(hash, 16777619);
  }
  return {
    prefixHash: (hash >>> 0).toString(16).padStart(8, '0'),
    modelId: isGemini4Available ? 'gemini-4-argon-medium' : 'gemini-3.8-flash',
    estimatedTokens: Math.ceil(staticPrefixText.length / 4)
  };
}

Sovereign Execution, Token Efficiency & Invariants

DimensionSovereign Mandate & Deterministic Contract
Frontier Model CascadeMedium / High (GPT-5.6 Sol Medium, Gemini 4 Argon, Claude Sonnet 5.5 High, Grok 4.7 High Fast)
Availability FallbackGemini 4 Argon/Pro -> Gemini 3.8 Flash; Claude Opus 5.5 -> Claude Opus 4.6 (Zero unhandled missing-model errors)
KV-Cache & Token ProtocolPin static instructions & schemas at prompt prefix (kv-cache-prefix-optimizer); pass surgical CONTEXT_MAP.md slices (<250 tokens/call) during Swarm Fan-Out
SaaT CLI & MCP DispatchCLI: vibes skill exec kv-cache-prefix-optimizer <audit|eval|verify|generate|blueprint> / MCP: vibes_skill_dispatch, vibes_ast_query, vibes_compile_cache, vibes_optimize_budget, vibes_verify_gate
NFR & Anti-Slop InvariantsP99 API Gateway Latency < 85ms, OpenAPI 3.1 / TypeSpec strict schema parity, RFC 9457 Problem Details error contracts, Idempotency-Key enforcement; 100% complete zero-placeholder output verified via node scripts/check-anti-slop.js --strict


Bahasa Indonesia

Integrasi Orkestrasi

  • Hulu & Orkestrasi: zero-to-prod-orchestrator (Integrasi agen AI Fase 4), brainstorming, session-memory-manager.
  • LLM Frontier & Caching Model: frontier-ai-models-expert (spesifikasi caching Gemini 4 Argon/Pro, Claude 5.5 Sonnet/Opus, Claude Fable 5.1, GPT-5.6 Sol, Grok 4.7), gemini-agent-booster (caching konteks native Google 2M+), vercel-ai-sdk-expert (kontrol cache provider).
  • FinOps & Eksekusi Adaptif: llm-finops-router (kalkulasi biaya & routing cache), adaptive-model-cascade (prefix tingkat cascade), thinking-budget-orchestrator (pinning prefix dengan token penalaran).
  • Rekayasa Prompt & Context Window: ai-prompt-engineering-expert (kanonikalisasi prompt), context-window-engineer (sliding window konteks besar).

Deskripsi

Panduan produksi untuk merekayasa awalan (prefix) prompt yang deterministik, mengunci batas KV-cache, dan memaksimalkan penggunaan ulang konteks pada model frontier akhir 2026 (Google Gemini 4 Argon / Pro context caching, Anthropic Claude 5.5 / 5.1 prompt caching, OpenAI GPT-5.6 Sol prefix caching, dan xAI Grok 4.7). Memberikan arsitektur yang menjamin tingkat keberhasilan cache (cache hit rate) di atas 90% melalui pengurutan definisi tool kanonikal, serialisasi JSON stabil, dan partisi konteks dinamis.

Kondisi Pemicu

Aktifkan skill ini ketika:

  • Mengelola agen berkonteks besar (>100k token) dengan biaya input token berulang yang signifikan.
  • Mengalami latensi tinggi pada Time-to-First-Token (TTFT) saat percakapan atau coding loop interaktif.
  • Mengonfigurasi parameter caching model (cache_control: { type: 'ephemeral' } atau Gemini explicit caching).
  • Merancang instruksi sistem, skema tool, dan peta repositori untuk sesi multi-turn.

Konsep Inti & Pola Praktik

1. Anatomi Prompt Ber-Cache Tinggi

Model frontier mencocokkan token awalan secara persis (prefix matching). Perubahan satu karakter saja di awal prompt akan merusak seluruh cache setelahnya:

  • Blok Statis (Terkunci): Instruksi sistem, daftar 171 skill, skema tool terurut, dan peta arsitektur proyek.
  • Titik Kunci Cache (Cache Pin): Menandai akhir blok statis dengan header kontrol cache.
  • Blok Volatil (Dinamis): Riwayat percakapan terkini dan hasil eksekusi tool giliran terakhir.
2. Serialisasi JSON Kanonikal

Kunci objek JSON wajib diurutkan secara alfabetis sebelum dikirimkan ke model agar representasi string biner tidak berubah antar permintaan.


Praktik Terbaik

  1. Jangan Taruh Timestamp di System Prompt: Masukkan waktu atau tanggal hanya pada pesan user paling akhir, bukan pada blok instruksi utama.
  2. Urutkan Definisi Tool Secara Alfabetis: Selalu lakukan sorting pada daftar nama fungsi dan parameter tool.
  3. Posisikan Data Dinamis di Bagian Akhir: Taruh seluruh dokumen referensi dan kode sebelum giliran pesan pengguna.
  4. Pantau Metrik Cache: Pantau token yang terbaca dari cache melalui telemetri guna mendeteksi jika terjadi cache bust yang tidak disengaja.
  5. Portabilitas Prefix Saat Fallback: Pertahankan struktur prefix sistem yang identik saat pengalihan ketersediaan model terjadi (Gemini 4 <-> Gemini 3.8 Flash, Claude Opus 5.5 <-> Claude Opus 4.6) agar pemanasan ulang (re-warming) KV-cache berlangsung instan tanpa inkonsistensi format.

Jebakan Umum yang Harus Dihindari

Praktik BurukDampak BurukSolusi Rekayasa
Menyisipkan ID sesi acak ke dalam system promptCache batal 100% pada setiap sesi baruPindahkan ID sesi ke header aplikasi di luar prompt
Urutan tool berubah-ubah dari Object.values(tools)Representasi string berubah dan membatalkan KV cacheUrutkan tool secara alfabetis berdasarkan namanya
Mengubah redaksi instruksi di tengah percakapanMembaca ulang 100k+ token dengan harga penuhKunci template instruksi dalam keadaan statis dan terversi

Matriks Eksekusi Berdaulat, Efisiensi Token & Invarian

DimensiMandat Berdaulat & Kontrak Deterministik
Kaskade Model FrontierMedium / High (GPT-5.6 Sol Medium, Gemini 4 Argon, Claude Sonnet 5.5 High, Grok 4.7 High Fast)
Invarian Fallback KetersediaanGemini 4 Argon/Pro -> Gemini 3.8 Flash; Claude Opus 5.5 -> Claude Opus 4.6 (Bebas gagal saat model belum tersedia/kuota penuh)
Protokol Hemat Token & KV-CacheKunci instruksi & skema statis di prefix awal (kv-cache-prefix-optimizer); kirim potongan CONTEXT_MAP.md (<250 token/panggilan) saat Fan-Out
Eksekusi SaaT CLI & MCPCLI: vibes skill exec kv-cache-prefix-optimizer <audit|eval|verify|generate|blueprint> / MCP: vibes_skill_dispatch, vibes_ast_query, vibes_compile_cache, vibes_optimize_budget, vibes_verify_gate
Invarian NFR & Anti-SlopLatensi P99 API < 85ms, paritas skema ketat OpenAPI 3.1 / TypeSpec, kontrak error RFC 9457 Problem Details, penegakan Idempotency-Key; kode 100% tuntas tanpa placeholder diverifikasi melalui node scripts/check-anti-slop.js --strict

Frequently asked questions

What does the Kv Cache Prefix Optimizer AI skill do?

Deterministic prompt prefix engineering & KV-cache hit optimization / Rekayasa prefix prompt deterministik & optimasi cache KV.

Why use Kv Cache Prefix Optimizer on TypingMind?

Because you install it once and use it with any model. Kv Cache Prefix Optimizer is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Kv Cache Prefix Optimizer in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/roedyrustam/vibes-plug/tree/main/skills/kv-cache-prefix-optimizer. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Kv Cache Prefix Optimizer?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Kv Cache Prefix Optimizer?

As many as you like. As long as a model supports skills, you can use Kv Cache Prefix Optimizer with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Kv Cache Prefix Optimizer AI skill free?

Yes. It is published on GitHub by roedyrustam under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇