01
Canonical prefix
Стабільні instructions, tool schemas, examples і shared context серіалізуються однаково.
AI Atlas · Concept · Intermediate
Повторне використання обчислень для незмінного префікса 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
01
Стабільні instructions, tool schemas, examples і shared context серіалізуються однаково.
02
User input, timestamp, request ID та інші мінливі поля розміщуються після reusable prefix.
03
API знаходить сумісний cached prefix за власними правилами, scope, model і TTL.
04
Модель все одно генерує новий output; cache не повертає збережену відповідь.
05
Application записує cache-read/write tokens, latency, model і prefix fingerprint.
Схема показує logical pipeline, а не внутрішню реалізацію конкретного provider.
| 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 cache | Retrieval candidates, query transform або evidence pack. | Cached retrieval layer; generation може бути новою. | ACL, freshness, deletion та index-version drift. |
Current provider contracts
Спільною є ідея повторюваного prefix. Automatic/explicit mode, breakpoint, minimum length, TTL, scope та telemetry не можна переносити між API без перевірки актуальної документації.
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.
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.
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 у документації моделі.
Signal: Cache-read tokens близькі до нуля, хоча workload повторюється.
Control: Canonical serialization; static-first layout; timestamps, IDs і user data лише у suffix.
Signal: Команда рапортує hit rate без cache-eligible input tokens.
Control: cache_read_tokens / eligible_repeated_prefix_tokens за model, route і prefix version.
Signal: Cache writes дорожчі за reads, бо prefix використали один раз.
Control: Replay traffic distribution; рахувати cost per verified task, не discount окремого token class.
Signal: Tenant або user context потрапив у shared reusable prefix.
Control: Cache identity включає security scope; sensitive variable data після shared boundary; negative isolation tests.
Signal: Нова instruction або revoked tool не діє через стару application configuration.
Control: Policy/tool version у fingerprint; deliberate invalidation; canary і rollback до known-good version.
Signal: Workflow покладається на cache як на durable state.
Control: Authoritative state у database/workflow store; cache — лише optimization layer.
Signal: Нижча latency оголошена кращою task quality.
Control: Окремі quality evals; caching має бути output-equivalent у межах accepted nondeterminism.
Signal: Один adapter припускає однакові TTL, breakpoints і usage fields.
Control: Capability-aware provider adapters та contract tests для кожного model/API version.
Practical example
Команда формує 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.
На representative traffic зафіксуйте input/output tokens, latency, cost і verified task outcome без нової cache policy.
Визначте model, instruction version, ordered tools/schema, shared context version, security scope і serializer.
Історичні sanitized requests покажуть prefix reuse distribution і потенційні writes, reads та misses без vendor-independent savings claim.
Обчислюйте candidate prefix identity і telemetry, не змінюючи user-visible result.
Увімкніть caching для bounded route/cohort; порівняйте usage fields, p50/p95 latency, errors і task verdicts.
Просувайте тільки якщо pre-registered cost/latency gates проходять без quality, security або freshness regression.
Зміна model, tools, policy, serializer або provider contract запускає targeted replay; miss spike стає diagnosable incident.
Це provider-side повторне використання обчислень для незмінного початку LLM-запиту. Воно може зменшувати billed input cost і latency, але модель генерує нову відповідь, а cache hit залежить від точного provider contract.
Ні. Це головна відмінність від semantic response cache: повторно використовується обробка prefix, а не готовий output.
Зміна будь-якого елемента 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.
Порівняйте canary з baseline на однакових task slices: cache reads/writes, uncached input, p50/p95 latency, errors, total cost і verified task outcome. Не екстраполюйте discount токена на весь TCO.
Automatic caching, exact-prefix matching, prompt layout and usage telemetry.
Boundary: Current OpenAI API behavior; not a universal provider contract or guaranteed saving.
Automatic/explicit caching, breakpoints, prefix hierarchy, TTL and cache usage semantics.
Boundary: Model and platform constraints change; current documentation must be checked before rollout.
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.