Перейти до основного вмісту

AI Atlas · Concept · Intermediate

Prompt Caching

Повторне використання обчислень для незмінного префікса LLM-запиту, щоб зменшити provider-billed input cost і latency без повторного використання готової відповіді.

Ключова ідея: стабільне — спочатку, змінне — наприкінці. Але production-рішення потребує не лише правильного prompt layout: потрібні versioned prefix identity, security scope, provider-specific adapter, usage evidence та rollback.

Автор: AI Magister Editorial Team · Огляд: AI Magister Technical Review · Перевірено 2026-08-23

Explanatory visual

Від canonical prefix до перевіреного cache hit

01

Canonical prefix

Стабільні instructions, tool schemas, examples і shared context серіалізуються однаково.

02

Variable suffix

User input, timestamp, request ID та інші мінливі поля розміщуються після reusable prefix.

03

Provider match

API знаходить сумісний cached prefix за власними правилами, scope, model і TTL.

04

Fresh generation

Модель все одно генерує новий output; cache не повертає збережену відповідь.

05

Usage evidence

Application записує cache-read/write tokens, latency, model і prefix fingerprint.

Схема показує logical pipeline, а не внутрішню реалізацію конкретного provider.

Не плутайте три різні cache layers

LayerЩо reuseЩо повертаєГоловний ризик
Prompt cachingВнутрішнє опрацювання однакового prompt prefix.Нову model response.Prefix miss, provider scope/retention, stale shared context.
Semantic response cacheГотову відповідь для exact або схожого query.Попередній application output.Stale або contextually wrong answer, cross-user leakage.
RAG cacheRetrieval candidates, query transform або evidence pack.Cached retrieval layer; generation може бути новою.ACL, freshness, deletion та index-version drift.

Current provider contracts

OpenAI, Anthropic і Gemini реалізують різні control surfaces

Спільною є ідея повторюваного prefix. Automatic/explicit mode, breakpoint, minimum length, TTL, scope та telemetry не можна переносити між API без перевірки актуальної документації.

OpenAI

Prompt Caching автоматично працює для eligible requests. Exact prefix match є критичним; static instructions, tools, schemas і examples треба ставити на початку, variable content — наприкінці.

Verify: Перевіряйте cached_tokens у response usage та versionуйте model, tools і prefix serializer. Наявність feature не гарантує hit для конкретного traffic shape.

Anthropic

Claude підтримує automatic та explicit caching. Explicit cache_control визначає breakpoint; prompt prefix має порядок tools → system → messages, а documented TTL і minimum cacheable length залежать від поточного model/platform contract.

Verify: Записуйте cache_creation_input_tokens і cache_read_input_tokens. Зміна content до breakpoint, tools або окремих thinking settings може інвалідувати cache.

Google Gemini

Gemini API розрізняє implicit caching на supported models і explicit context caching через CachedContent з налаштованим TTL. Explicit cache можна посилати в наступних generation requests.

Verify: Зберігайте cached-content ID, model, create/expire time і usage metadata; перевіряйте актуальні minimums та pricing у документації моделі.

Failure modes та controls

Prefix churn

Signal: Cache-read tokens близькі до нуля, хоча workload повторюється.

Control: Canonical serialization; static-first layout; timestamps, IDs і user data лише у suffix.

Wrong denominator

Signal: Команда рапортує hit rate без cache-eligible input tokens.

Control: cache_read_tokens / eligible_repeated_prefix_tokens за model, route і prefix version.

Write amplification

Signal: Cache writes дорожчі за reads, бо prefix використали один раз.

Control: Replay traffic distribution; рахувати cost per verified task, не discount окремого token class.

Cross-scope design

Signal: Tenant або user context потрапив у shared reusable prefix.

Control: Cache identity включає security scope; sensitive variable data після shared boundary; negative isolation tests.

Stale policy prefix

Signal: Нова instruction або revoked tool не діє через стару application configuration.

Control: Policy/tool version у fingerprint; deliberate invalidation; canary і rollback до known-good version.

Cache equals memory

Signal: Workflow покладається на cache як на durable state.

Control: Authoritative state у database/workflow store; cache — лише optimization layer.

Quality assumed

Signal: Нижча latency оголошена кращою task quality.

Control: Окремі quality evals; caching має бути output-equivalent у межах accepted nondeterminism.

Provider semantics copied

Signal: Один adapter припускає однакові TTL, breakpoints і usage fields.

Control: Capability-aware provider adapters та contract tests для кожного model/API version.

Practical example

Support copilot із 40 tool schemas

Команда формує prefix із versioned policy, ordered tool schemas і approved examples. Tenant ID, user permissions, ticket text та current timestamp залишаються у suffix. Prefix fingerprint містить model, policy version, tool-bundle hash і tenant security scope. Canary порівнює cache reads/writes, latency, total model cost, tool-call validity та accepted-resolution rate. Якщо policy або tool schema змінюється, новий fingerprint навмисно створює miss; попередню версію можна повернути, але revoked capability не можна “відкотити” всупереч policy.

Rollout без вигаданих savings

P0 · Baseline

На representative traffic зафіксуйте input/output tokens, latency, cost і verified task outcome без нової cache policy.

P1 · Fingerprint

Визначте model, instruction version, ordered tools/schema, shared context version, security scope і serializer.

P2 · Replay

Історичні sanitized requests покажуть prefix reuse distribution і потенційні writes, reads та misses без vendor-independent savings claim.

P3 · Shadow

Обчислюйте candidate prefix identity і telemetry, не змінюючи user-visible result.

P4 · Canary

Увімкніть caching для bounded route/cohort; порівняйте usage fields, p50/p95 latency, errors і task verdicts.

P5 · Promote

Просувайте тільки якщо pre-registered cost/latency gates проходять без quality, security або freshness regression.

P6 · Operate

Зміна model, tools, policy, serializer або provider contract запускає targeted replay; miss spike стає diagnosable incident.

Production checklist

  • ✓ Reusable prefix визначений байтово/структурно, а не як “приблизно той самий prompt”.
  • ✓ Static instructions, tools, schemas і shared context передують variable suffix.
  • ✓ Model, prefix version, security scope та provider mode входять у fingerprint.
  • ✓ Cache не використовується як durable memory або authorization mechanism.
  • ✓ Sensitive prefixes перевірені проти current provider data-control contract.
  • ✓ Telemetry розділяє cache writes, reads, uncached input, output і retries.
  • ✓ Економіка рахується на representative reuse distribution і verified tasks.
  • ✓ Quality/security/freshness evals проходять незалежно від cache-hit metric.
  • ✓ Canary має kill switch: вимкнути caching або повернути previous prefix version.
  • ✓ Зміна tools, policy, model чи serializer запускає regression replay.

FAQ

Що таке prompt caching?

Це provider-side повторне використання обчислень для незмінного початку LLM-запиту. Воно може зменшувати billed input cost і latency, але модель генерує нову відповідь, а cache hit залежить від точного provider contract.

Чи prompt caching повертає стару відповідь?

Ні. Це головна відмінність від semantic response cache: повторно використовується обробка prefix, а не готовий output.

Що найчастіше ламає cache hit?

Зміна будь-якого елемента reusable prefix: порядку tools, schema, system instruction, examples, whitespace/serialization або model settings, які provider включає у cache identity.

Чи можна кешувати персональні дані?

Технічна можливість не є дозволом. Перевірте provider data controls, retention, region і isolation; не змішуйте tenants/users у shared identity та мінімізуйте sensitive content.

Як виміряти користь без вигаданого ROI?

Порівняйте canary з baseline на однакових task slices: cache reads/writes, uncached input, p50/p95 latency, errors, total cost і verified task outcome. Не екстраполюйте discount токена на весь TCO.

Джерела і межі тверджень

OpenAI API — Prompt caching ↗

Automatic caching, exact-prefix matching, prompt layout and usage telemetry.

Boundary: Current OpenAI API behavior; not a universal provider contract or guaranteed saving.

Claude Platform — Prompt caching ↗

Automatic/explicit caching, breakpoints, prefix hierarchy, TTL and cache usage semantics.

Boundary: Model and platform constraints change; current documentation must be checked before rollout.

Gemini API — Context caching ↗

Implicit and explicit context caching, CachedContent lifecycle and TTL concepts.

Boundary: Provider capability evidence, not proof of quality, latency or savings for a deployment.

AI-Magister не заявляє універсального cache-hit rate, savings, latency improvement або ROI. Prefix fingerprint, security boundaries, rollout gates і incident policy є engineering synthesis, яку треба адаптувати та перевіряти на власному workload.

Продовжити кластер