diff --git a/promptbook/prompts.json b/promptbook/prompts.json index 44a0d4e..97a3b7d 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -1082,6 +1082,26 @@ ], "formatNotes": "All three. Point the tool at the model client, the parse sites, tool executors, the schema directory, and the eval fixtures. Copilot: llm-structured-output path instructions plus those files in agent mode (or save the prompt as `.github/prompts/enforce-llm-structured-output.prompt.md`). Claude Code: the llm-structured-output-guardrails skill plus the parser, validator, and test files. Codex: the AGENTS.md LLM structured output section, then the diff. Leave prompt-injection trust maps, routing fallback, PII redaction, eval gate wiring, and price tables to their own skills.", "body": "Task: Make the LLM calls I specify return schema-valid JSON, or a typed failure, every time. Use provider-native schema mode or strict tools where the target supports them, and validate every document on the server against a versioned schema anyway. Check the stop reason before parsing. Allow one bounded repair, then fail closed. Treat tool-call arguments as untrusted input. Count outcomes without logging payloads, and add schema-conformance fixtures to CI. Finish with a minimal diff, the schemas, and tests.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Service or gateway and module: {{APP_NAME}} at {{APP_PATH}}\n- Stack: {{STACK}} (Spring Boot version and Jackson 2 or 3; Spring AI | LangChain4j | plain HTTP client | mixed)\n- Providers and targets: {{PROVIDERS}} (Azure OpenAI, OpenAI, Anthropic, Amazon Bedrock, OpenRouter, other OpenAI-compatible) and which support native schema mode or strict tools\n- Structured calls: {{CALLS}} (call site → schema name and version → consumer)\n- Tools: {{TOOLS}} (tool name → side effect → who may call it, or \"none\")\n- Schema location: {{SCHEMA_DIR}} (default `src/main/resources/llm-schemas/`)\n- Validator: {{VALIDATOR}} (networknt json-schema-validator 3.x for Jackson 3, 2.x for Jackson 2, or the one the repo already uses)\n- Failure contract: {{FAILURE_CONTRACT}} (HTTP status and problem+json codes, or the internal result type)\n- Budget: {{BUDGET}} (route deadline, max output tokens, and whether one repair fits)\n- Observability: {{OBSERVABILITY}} (Micrometer | OpenTelemetry | both)\n- Eval gate: {{EVAL_GATE}} (existing eval CI job and fixture path, or \"none\")\n- Pain: {{PAIN}} (parse exceptions | refusals parsed as data | truncated JSON | unbounded retries | unsafe tool calls | none)\n\nRequirements:\n\n1. Inventory\n - Read {{APP_PATH}}: every place model output is parsed, every tool executor, every retry around a model call, and any regex that pulls `{...}` out of text\n - Table: call site | schema (or none) | mode (native | json_mode | prompt_only | tool) | stop reason checked? | server-side validator? | retry policy | consumer\n - Flag `readValue` on raw completion text in a broad catch, unbounded \"retry until it parses\" loops, brace-closing or quote-fixing helpers, `ScriptEngine`/SpEL/reflection/polymorphic typing driven by output, and tenant or user IDs taken from tool arguments\n\n2. Schemas in {{SCHEMA_DIR}}\n - One file per schema and version (`ticket_triage.v2.json`), Draft 2020-12, `$id` set, stored in the repo\n - Object root. `additionalProperties: false` on every object. Every property in `required`; use a nullable type where a value can be absent\n - Decisions are `enum`, each with an explicit escape value (`unknown`, `insufficient_input`). No free-form unions or \"any JSON\" fields. Real variants use a discriminator enum and one closed object per kind\n - Bounds on numbers, arrays, and ID-shaped strings\n - One source of truth: generate from the Java record or test that the record and the schema agree\n - Check each schema against the strict-mode subset of every target in {{PROVIDERS}}. When a keyword is rejected, enforce that rule in the server-side validator or in code. Do not delete the rule\n\n3. Request mode\n - Use native schema mode (OpenAI/Azure OpenAI `json_schema` with strict, Anthropic JSON outputs) or strict tool definitions where the target supports them. Choose per target from capability config, not from a model-name string\n - Targets without support stay explicit as `json_mode` or `prompt_only`, and get the same server-side checks\n - Disable parallel tool calls on a request where they conflict with strict schemas on that provider\n\n4. Ordered response checks (each failure is a typed outcome; nothing falls through to the parser)\n - Stop reason first. Normal completion continues. Truncation (`length`, `max_tokens`, `max_output_tokens`, incomplete status, context-window stop) → `truncated`. Refusal (a `refusal` field or item, `stop_reason: refusal`) → `refused`. Content filter or guardrail stop → `filtered`. Anything unmapped → `unexpected_stop`\n - Extract from the field the mode uses (message content, or the named tool call's arguments). Exactly one document where one is expected. No searching prose for `{`\n - Byte cap before parsing → `oversize`\n - Strict parse on a dedicated Jackson reader, not the shared mapper: `STRICT_DUPLICATE_DETECTION`, `FAIL_ON_TRAILING_TOKENS`, and `FAIL_ON_UNKNOWN_PROPERTIES` enabled explicitly (Jackson 3 and Spring Boot's default mapper leave unknown properties allowed), no comments or trailing commas → `parse_error`\n - Validate with {{VALIDATOR}} → `schema_invalid` with a list of `{path, keyword}` pairs. For `required`, add the missing property name to the path\n - Bind to the record, then run business rules the schema cannot express (cross-field totals, referenced ID exists and belongs to this tenant) → `business_rule_invalid`\n\n5. Validator setup\n - One registry bean with an explicit Draft 2020-12 dialect. Load schemas from the classpath at startup, compile once, preload validators so a broken `$ref` fails at boot, and fail startup when a configured schema is missing. No remote `$ref` fetching\n - Turn on format assertions if any field relies on `format`, or use `pattern`, and test a bad value\n - Validate in native mode too\n\n6. One repair, then fail closed\n - `parse_error`, `schema_invalid`, `business_rule_invalid`: re-ask once on the same target with the same schema and mode, adding a short system-authored message that lists the `{path, keyword}` violations. No field values or user text in that message\n - `truncated`: one retry with a higher output-token cap only if {{BUDGET}} allows; otherwise fail. Never stitch a \"continue\" onto a structured document\n - `refused`, `filtered`, `unexpected_stop`, `oversize`, or any second failure: no retry\n - The repair counts against the route deadline and token budget. It is not a provider fallback. Never relax the schema, drop strict mode, or switch to prompt-only on the retry\n - Remove guessing fixers. A deterministic normalizer is allowed only for a documented case (one Markdown code fence around otherwise valid JSON from a prompt-only target), and its use is counted\n - Return {{FAILURE_CONTRACT}}: problem+json codes such as `llm_output_invalid`, `llm_output_refused`, `llm_output_truncated`, or a sealed result type. Nothing downstream receives a partial or default-constructed record\n\n7. Never evaluate output\n - No ScriptEngine, SpEL, OGNL, Groovy, template evaluation, reflection on model-supplied names, or polymorphic Jackson typing on these records\n - Behavior-selecting fields are enums mapped in a `switch`. Strings that reach SQL, a shell, a URL, HTML, or a log are parameterized or encoded for that sink\n\n8. Tool calls ({{TOOLS}})\n - Tool name on this route's allowlist, checked before argument parsing\n - Arguments validated against the server's copy of the tool schema, then bound\n - Authorize as the end user. Tenant and user come from the authenticated context, never from arguments. Every ID is checked against what this caller may access\n - Allowlist target-selecting values (hosts, queues, tables, paths, domains). Bound amounts and limits\n - Side-effecting tools get a server-generated idempotency key and, where high impact, a confirmation step\n - A rejection goes back to the model as a short tool error and shares the single repair limit\n\n9. Metrics and logs ({{OBSERVABILITY}})\n - `llm_structured_output_total` labels: `route`, `schema`, `mode`, `outcome` (`valid`, `repaired`, `parse_error`, `schema_invalid`, `business_rule_invalid`, `refused`, `truncated`, `filtered`, `unexpected_stop`, `oversize`)\n - `llm_structured_output_violations_total` labels: `schema`, `keyword`. Paths go in log fields, not labels\n - `llm_tool_call_rejected_total` labels: `route`, `tool`, `reason` (`unknown_tool`, `schema_invalid`, `not_authorized`, `not_allowlisted`)\n - Log request ID, route, schema version, mode, target, stop reason, outcome, violation pairs, and whether repair ran. Never the completion, the arguments, the failing value, or a hash of it\n\n10. Tests and CI ({{EVAL_GATE}})\n - Offline fixtures per schema version, run on every PR: valid docs, missing required, extra property, wrong enum, disallowed null, duplicate key, truncated object, refusal, content-filter stop, prose around JSON, two tool calls where one was expected, unknown tool name. Each asserts the outcome, the violation list, and that the consumer or tool stub saw nothing\n - Repair: stub returns invalid then valid → two calls, `repaired`, and the repair message contains paths and keywords but no fixture values. Stub returns invalid twice → two calls, typed failure, no third call\n - Truncation and refusal: no parse attempt, correct outcome, no repair call for the refusal\n - Tool authz: valid arguments naming another tenant's ID → `not_authorized`, zero tool stub calls\n - Schema and record agree; each schema passes the strict-subset check for every target that uses it\n - Live conformance (scheduled or when prompt, model, or schema changes): first-attempt `valid` rate, `repaired` rate, and failure rate per schema version, reported into the existing eval gate. Fail below the recorded floor or on any `unexpected_stop`. Do not build a second gate\n - Synthetic fixtures only\n\n11. Verification\n - Inventory table from step 1, updated\n - Schema list with version, mode per target, and the rules enforced only server-side\n - Outcome mapping table: provider stop reason → outcome → HTTP code or result type\n - Tests added and what each asserts\n\nConstraints:\n- Minimal diff. Match the module's config, error, and test style. No new HTTP client, no second JSON library, and no second validator if one is already present.\n- No real customer text, live endpoints, or secrets in fixtures. Stub providers for every test except the scheduled live conformance run.\n- Do not weaken validation, raise the repair limit, or loosen `additionalProperties` to make a test pass.\n- Leave prompt-injection trust maps and output-sink encoding, routing and fallback (including `fallbackOnBadRequest`), PII redaction, eval gate wiring, and price tables to their existing skills. Call their hooks where this stage sits next to them.\n- Copilot, Claude Code, and Codex: concrete diffs, the inventory table, and a checklist. Do not paste this prompt into AGENTS.md.\n\nOutput format:\n1. Inventory table and the parse sites that still trust raw output\n2. Schemas and config diff (mode per target, validator bean, outcome enum)\n3. Code diff (ordered checks, repair, failure contract, tool gate, counters)\n4. Tests added and what each asserts, including the repair and tool-authz cases\n5. Outcome mapping table and the conformance floor per schema version\n\nStart from {{APP_PATH}}. Land the stop-reason checks, the server-side validator, and the offline fixtures before turning on a new schema version or a new tool.\n" + }, + { + "id": "add-llm-gateway-caching", + "title": "Add Safe Prompt, Exact, and Semantic Caching to LLM Routes", + "whenToUse": "Cut LLM cost and latency with caching without cross-tenant leaks, stale answers, or wrong semantic hits — prompt reordering for provider prefix caching, an opt-in exact response cache with a full key, a semantic tier only inside hard partitions with a threshold chosen from labeled near-miss pairs, invalidation by version and erasure, cache headers, metrics, and CI tests.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "llm", + "caching", + "semantic-cache", + "prompt-caching", + "gateway", + "spring-boot" + ], + "formatNotes": "All three. Point the tool at the model client, prompt templates, the gateway route config, the cache store client, and the eval fixtures. Copilot: llm-caching path instructions plus those files in agent mode (or save the prompt as `.github/prompts/add-llm-gateway-caching.prompt.md`). Claude Code: the llm-gateway-caching-guardrails skill plus the route config and key builder. Codex: the AGENTS.md LLM caching section, then the diff. Leave price tables, routing fallback, PII redaction, structured output validation, and eval gate wiring to their own skills.", + "body": "Task: Add safe caching to the LLM routes I specify. Start with provider prompt caching, then an opt-in exact response cache, and add a semantic cache only on routes that qualify. No cache may serve one caller's answer to another, serve a stale answer after a model, prompt, or data change, or serve the answer to a different question. Finish with a minimal diff, config, and tests.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Gateway or service and module: {{APP_NAME}} at {{APP_PATH}}\n- Stack: {{STACK}} (Spring Boot version; Spring AI | LangChain4j | plain HTTP client | API Management or proxy policy)\n- Providers and targets: {{PROVIDERS}} (Azure OpenAI, OpenAI, Anthropic, Amazon Bedrock, OpenRouter, other OpenAI-compatible) and how each turns on prompt caching\n- Routes: {{ROUTES}} (route → deterministic? → user-specific? → RAG? → wrong-answer cost)\n- Cache store: {{STORE}} (Redis or Azure Managed Redis with vector search, pgvector, Azure AI Search, other) and whether it reports similarity or distance\n- Embedding model for semantic lookups: {{EMBEDDING_MODEL}} (or \"none yet\")\n- Tenancy and auth scope: {{TENANCY}} (where tenant and permission scope come from in the authenticated context)\n- Data rules: {{DATA_RULES}} (classification, retention, residency, erasure requirements)\n- Observability: {{OBSERVABILITY}} (Micrometer | OpenTelemetry | both) and the cost ledger that prices tokens\n- Eval gate: {{EVAL_GATE}} (existing eval CI job and fixture path, or \"none\")\n\nRequirements:\n\n1. Inventory\n - Table: route | model | deterministic? | user-specific? | RAG (corpus version source)? | estimated repeat rate | wrong-answer cost | proposed tier (none | prompt cache | exact | semantic) | reason\n - Flag any existing cache whose key is the user message alone, any global semantic index, missing TTLs, and thresholds with no labeled data behind them\n\n2. Provider prompt caching\n - Reorder each prompt: system instructions, tool definitions, schemas, examples, and long reference text first; user message, retrieved chunks, timestamps, and IDs last\n - Make the static prefix byte-stable (deterministic key order for tool and schema JSON, stable tool order)\n - Turn on caching per target from capability config: automatic where the provider does it, explicit markers (for example `cache_control` or cache checkpoints) where required. Keep minimum lengths, lifetimes, and write premiums in config with a checked-on date and doc link\n - Mark only prefixes that repeat within the lifetime when writes cost extra\n - Record cached-read and cache-write token counts from every response and hand them to the cost ledger. Do not hard-code prices here\n\n3. Exact response cache (opt-in per route, default off)\n - Key: SHA-256 of a canonical serialization of tenant, auth scope (when the answer depends on it), route, resolved model and version (not an alias), prompt template version, tool definitions version, normalized redacted messages, generation parameters (temperature, top_p, max_tokens, response format and schema version, tool choice, seed), and corpus or index version plus retrieved chunk IDs for RAG. Prefix with a cache format version. No raw prompt in the key\n - Store only complete responses: normal stop reason, schema-valid where a schema applies, not refused, filtered, or truncated, no tool calls, no streaming partials\n - Store the redacted body, key fields as metadata, model, prompt version, created time, TTL, and originating request ID. Encrypt at rest per {{DATA_RULES}}. Every entry has a TTL; short for user-specific content\n - Skip routes whose answer depends on time or live data the key does not capture\n\n4. Semantic cache (only for routes the inventory marks semantic)\n - Hard partition on tenant, auth scope, route, resolved model, prompt and tool versions, schema version, embedding model and version, and corpus version. Similarity search runs only inside that partition, and the partition is re-verified on the returned entry\n - Embed the normalized, redacted question plus any context that changes the answer. Routes where unembedded context changes the answer are not eligible. Skip multi-turn requests past a configured message count\n - Requests carrying IDs, amounts, dates, or code skip the semantic tier\n - Build a labeled pair file per route from redacted real traffic: pairs that should share an answer and near-miss pairs that must not (different action words, negations, different IDs or amounts). Choose the threshold from the route's allowed false-hit rate. Write in config whether the store measures similarity (higher is closer) or distance (lower is closer)\n - Stricter threshold or no semantic tier for money, policy, eligibility, health, security, or account-specific answers\n - Timeouts on the embedding call and vector query; on timeout or error, call the model\n\n5. Invalidation and control\n - Version bumps (model, prompt, tools, schema, embedding model, corpus) change the key or partition, so old entries are unreachable and expire by TTL\n - Source tags on RAG entries; a data-change event invalidates tagged entries\n - Erasure: deleting a user or tenant removes every entry in that partition\n - Per-route, per-tier kill switch in config and a purge command for a partition\n\n6. Response semantics and security\n - `X-Cache: HIT-EXACT | HIT-SEMANTIC | MISS | BYPASS` and the entry's creation time on responses\n - Trusted internal callers may bypass. End users cannot force writes into shared partitions. Anonymous or untrusted traffic never writes to a shared partition\n - Hits still pass caller-dependent output checks (authorization on referenced records, redaction for the current audience)\n - Partition values come from the authenticated context, never from request fields\n - Hits are recorded with zero model tokens; semantic lookups record embedding cost\n\n7. Metrics and logs ({{OBSERVABILITY}})\n - `llm_cache_requests_total` labels: `route`, `tier`, `result` (`hit`, `miss`, `bypass`, `ineligible`, `error`)\n - `llm_cache_semantic_score` histogram per route\n - `llm_prompt_cache_tokens_total` labels: `route`, `provider`, `kind` (`read`, `write`)\n - `llm_cache_false_hit_total` labels: `route`, `tier`, fed by feedback, quick re-asks, or audit\n - Logs: request ID, route, tier, result, score, matched entry's request ID. No prompt or answer text, and no tenant names in labels\n\n8. Tests and CI ({{EVAL_GATE}})\n - Changing any key component produces a miss; the same request from two tenants or two auth scopes never shares an entry\n - Refused, truncated, filtered, schema-invalid, tool-call, and partial responses are never stored; ineligible routes never read or write\n - Near-miss pair file per semantic route runs in CI with the configured embedding model and threshold. Fail on any must-not-match hit or a false-hit rate above the route limit. Report into the existing eval gate; do not build a second one\n - Version bump makes old entries unreachable; erasure leaves zero entries\n - Cache store down or slow: requests still succeed through the model within the route deadline\n - Rendered prompt prefix is byte-identical across two requests with different user messages\n - Synthetic or redacted fixtures only\n\n9. Verification\n - Updated inventory table with the chosen tier per route\n - Key and partition field list, TTLs, thresholds with measure direction, and the labeled-set results per semantic route\n - Before and after: cached-token share, hit rate per tier, and p95 latency on misses\n\nConstraints:\n- Minimal diff. Reuse the existing Redis or vector store client and cache config style; no second cache library.\n- Caching is off by default for every route until config opts it in.\n- Do not lower a threshold, widen a partition, or skip an eligibility check to make a test pass.\n- Leave price tables, routing and fallback, PII redaction rules, structured output validation, retrieval quality, and eval gate wiring to their existing skills. Call their hooks where caching sits next to them.\n- Copilot, Claude Code, and Codex: concrete diffs, the inventory table, and a checklist. Do not paste this prompt into AGENTS.md.\n\nOutput format:\n1. Inventory table and the tier chosen per route\n2. Prompt reordering diff and prompt-cache config per target\n3. Exact cache diff (key builder, eligibility, storage, header)\n4. Semantic cache diff and labeled-set results, if any route qualifies\n5. Invalidation, kill switch, metrics, and tests added with what each asserts\n\nStart from {{APP_PATH}}. Ship prompt caching and the exact cache with their tests before turning on any semantic route.\n" } ] } diff --git a/skillbook/skills.json b/skillbook/skills.json index 2a94ba8..e67e943 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -1080,6 +1080,26 @@ ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/llm-structured-output.instructions.md` with applyTo for `**/llm/**`, `**/*Schema*.java`, `**/*Tool*.java`, `**/gateway/**`, and `**/llm-schemas/**`. Optional on-demand procedure at `.github/skills/llm-structured-output-guardrails/SKILL.md`. Claude Code: `.claude/skills/llm-structured-output-guardrails/SKILL.md` plus a CLAUDE.md fact that model JSON and tool arguments are validated server-side against versioned schemas before use, with one repair and then a typed failure. Codex: a short \"LLM structured output\" brief in root `AGENTS.md` (schema location, validator bean, outcome enum, conformance test command) while the procedure stays in SKILL.md. Pair with llm-app-prompt-injection-guardrails for tool agency and output-sink encoding, llm-gateway-routing-fallback-guardrails for capability skips and fallbackOnBadRequest, llm-pii-redaction-guardrails for anything logged, llm-eval-ci-regression-gate for the gate that reads the conformance rate, and llm-cost-latency-budget-guardrails for the repair attempt's budget. This skill owns the schema contract, the check order, validation, repair, and the tool-argument gate.", "body": "# Skill: LLM Structured Output Guardrails\n\n## Goal\n\nWhen a Java or Spring Boot service, or an LLM gateway, needs JSON from a model (an extraction record, a classification, a routing decision, or the arguments of a tool call), the code that consumes it gets either a document that passed the server's own schema check or a typed failure. It never gets \"probably JSON\", a half-finished object, or a refusal that was parsed as data.\n\nThis skill owns the output contract: the schema and its version, the provider mode that asks for it, the stop-reason checks before parsing, server-side validation, the single bounded repair attempt, the fail-closed result, tool-call arguments as untrusted input, counters for validation outcomes, and the conformance fixtures that keep the rate visible in CI.\n\nTrust boundaries, tool agency, and encoding output for HTML, SQL, or a shell stay in **llm-app-prompt-injection-guardrails**. This skill makes the payload well-formed. That skill decides what a well-formed payload is still not allowed to do. Capability-based target selection (`json_schema`, `tools`) and the `fallbackOnBadRequest` switch stay in **llm-gateway-routing-fallback-guardrails**. Redacting personal data before the call, and in anything logged after it, stays in **llm-pii-redaction-guardrails**. The CI gate wiring, golden-set versioning, and baselines stay in **llm-eval-ci-regression-gate**; this skill only adds the schema-conformance cases and the metric that gate reads. Token and cost accounting for the retry stays in **llm-cost-latency-budget-guardrails**. HTTP API contracts between services stay in **spring-boot-openapi-contract-guardrails**.\n\n\"Respond only with valid JSON\" in a prompt is a request, not a control. The control is this code path.\n\n## When to apply\n\n- A feature parses model output into a record, an enum, or a command, with Spring AI, LangChain4j, or a plain HTTP client\n- A tool-calling or agent loop where the model supplies arguments that the service executes\n- A gateway that forwards `response_format`, `output_config.format`, or tool definitions and has to behave the same across providers\n- A review that finds `objectMapper.readValue(...)` on raw completion text inside a broad `try/catch`, regex extraction of `{...}` from prose, or a retry loop with no limit\n- Moving from prompt-only JSON or legacy JSON mode to provider-native schema mode\n\n## Ask the provider for the schema, then still validate\n\nThere are three levels. Use the highest one the target supports, and validate on the server at every level.\n\n| Level | What it guarantees | Where it is set |\n|---|---|---|\n| Native schema mode (strict) | Output is generated against the supplied schema, except on refusal, truncation, or another stop condition | OpenAI and Azure OpenAI: `json_schema` response format or `strict` function tools. Anthropic: JSON outputs (`output_config.format`) and `strict: true` on tool definitions. Bedrock Converse and OpenAI-compatible routers: check the model's documented support and treat the rest as level 3 |\n| JSON mode | Syntactically valid JSON. No schema adherence | Legacy `json_object` response format and similar |\n| Prompt only | Nothing | Instructions plus examples |\n\nRules:\n\n- Pick the level per target from the gateway's capability list, not from the model name in a string. A target without `json_schema` is skipped or flagged by the routing skill; it is not sent the same request and expected to comply.\n- Strict modes accept a subset of JSON Schema, and the subset differs by provider. Public docs list which keywords are supported (typically `enum`, `anyOf`, `$defs`/`$ref`, numeric and array bounds, some `format` values) and which are rejected (often `allOf`, `not`, `if`/`then`/`else`, `dependentRequired`). When a keyword is rejected, move that rule into the server-side validator or into code. Do not delete it to get the request accepted.\n- Native mode does not make values correct. A well-formed record can still carry a wrong total, an invented ID, or a guess where the input had nothing to extract. Business rules are checked in code after the schema passes.\n- The first request with a new schema can be slower on some providers while the schema is compiled and cached. Warm it in a smoke test after deploy rather than on a user request.\n\n## Schema design\n\nDesign the schema for the consumer and for strict mode at the same time.\n\n- **Object root, closed objects.** The root is an object. Every object sets `additionalProperties: false`. Unknown keys are a validation error, not something Jackson silently drops.\n- **Required everything.** List every property in `required`. When a value can be absent, make it nullable (`\"type\": [\"string\", \"null\"]`) instead of optional, so \"missing\" and \"not known\" are the same explicit thing.\n- **Enums for decisions.** Labels, actions, statuses, and severities are `enum`. Add an explicit escape value (`unknown`, `insufficient_input`, `not_applicable`) so the model has a legal answer when the input does not fit. Without it, strict mode forces a guess.\n- **No free-form unions.** Avoid `anyOf` of unrelated shapes and \"any JSON\" fields. When variants are real, use a discriminator (`\"kind\": {\"enum\": [\"refund\", \"replacement\"]}`) with one closed object per kind, and keep it within the provider's nesting limits.\n- **Bounded values.** `minimum`/`maximum`, `maxItems`, and `pattern` or `maxLength` where the provider and your validator support them. A field the consumer uses as an ID matches the ID's shape.\n- **No reasoning fields you do not need.** A `reasoning` or `explanation` string is free text inside a structured result. Keep it short and bounded if the product needs it, and never feed it to another system as an instruction.\n- **Versioned.** Each schema has a stable name and a version (`invoice_extract.v3`) stored in the repo, for example `src/main/resources/llm-schemas/invoice_extract.v3.json`, with `$id` set. The version travels with the request metadata, the metric labels, and the eval fixtures. A breaking change is a new version, and both versions validate during the rollout.\n- **One source of truth.** Generate the schema from the Java record (Spring AI's bean output converter, LangChain4j's JSON schema support, or a schema generator in the build) or hand-write it and test that the record and the schema agree. Do not keep two drifting copies.\n\n```json\n{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://schemas.example.com/llm/ticket_triage.v2.json\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"schema_version\", \"category\", \"priority\", \"customer_ref\", \"summary\"],\n \"properties\": {\n \"schema_version\": { \"const\": \"ticket_triage.v2\" },\n \"category\": { \"enum\": [\"billing\", \"access\", \"outage\", \"other\", \"insufficient_input\"] },\n \"priority\": { \"enum\": [\"p1\", \"p2\", \"p3\", \"p4\"] },\n \"customer_ref\": { \"type\": [\"string\", \"null\"], \"pattern\": \"^CUS-[0-9]{8}$\" },\n \"summary\": { \"type\": \"string\", \"maxLength\": 400 }\n }\n}\n```\n\nCheck `const` and every other keyword against the target provider's strict subset before you rely on it in the request. The server-side validator enforces the full schema either way.\n\n## Order of checks on every response\n\nRun these in order. Each step that fails returns a typed outcome and stops; it never falls through to the parser.\n\n1. **Transport and provider error.** Owned by the routing skill. Nothing below runs on a non-2xx.\n2. **Stop reason.** Read it before touching the content.\n - Normal completion (`stop`, `end_turn`, `tool_use` / `tool_calls` when a tool call was expected): continue.\n - Truncation (`length`, `max_tokens`, `max_output_tokens`, an `incomplete` status, a context-window stop): outcome `truncated`. A cut-off object is not repaired by closing its braces.\n - Refusal (a separate `refusal` field or content item, `stop_reason: refusal`): outcome `refused`. The refusal text is not data and is not parsed against the schema.\n - Content filter or guardrail stop (`content_filter`, a guardrail intervention): outcome `filtered`.\n - Anything unrecognized: outcome `unexpected_stop`. Fail closed. Add the value to the mapping when you see it.\n3. **Extract.** Take the structured content from the field the mode uses (the message content in schema mode, the arguments of the named tool call in tool mode). Do not search prose for the first `{`. Exactly one document. Reject a response with zero or several when one was expected. When strict tool calling and parallel calls conflict on the provider, turn parallel calls off for that request.\n4. **Size.** Reject a document over the configured byte cap before parsing.\n5. **Parse.** Strict parser: no comments, no trailing commas, no single quotes, duplicate keys rejected, nothing after the document. Use a dedicated Jackson reader for these records and enable `STRICT_DUPLICATE_DETECTION`, `FAIL_ON_TRAILING_TOKENS`, and `FAIL_ON_UNKNOWN_PROPERTIES` on it explicitly. Jackson 3 turns unknown-property failure off by default, and Spring Boot's auto-configured mapper turns it off on Jackson 2, so do not rely on the shared mapper.\n6. **Validate** against the versioned schema with a JSON Schema validator (below). Collect all errors.\n7. **Bind** to the Java record, then run the business rules the schema cannot express (cross-field totals, a referenced ID exists and belongs to this tenant, a date is in range).\n8. **Use.** Only now does the value reach the caller, a tool, or a store.\n\n## Server-side validation in Java\n\nValidate even in native mode. The provider's guarantee does not cover refusal, truncation, a provider bug, a router that silently drops the schema parameter, a model swapped behind an alias, or a schema keyword the provider ignored.\n\n- **networknt json-schema-validator** is the common choice. The 3.x line targets Java 17+ and Jackson 3 (Spring Boot 4). The 2.x line targets Jackson 2 (Spring Boot 3). Its 2.x and later API uses a `SchemaRegistry` with an explicit dialect (Draft 2020-12) and returns a list of errors. Other maintained validators are fine if the repo already uses one; pick one, not two.\n- Load schemas from the classpath at startup, compile them once, and keep the registry as a singleton bean. Call `initializeValidators()` on each loaded schema so a broken `$ref` fails at boot instead of on the first request. Fail startup if a schema referenced in config is missing or does not compile. Do not fetch remote `$ref` targets at runtime (2.x and later leave remote fetching off by default; keep it off).\n- Since Draft 2019-09, `format` is an annotation unless assertion is turned on. If a field depends on `format` (`date`, `uuid`, `email`), enable format assertions in the validator's execution config or use a `pattern`, and test that a bad value fails.\n- Map each error to `{path, keyword}`, for example `{\"/priority\", \"enum\"}`. For `required`, the instance location is the parent object, so append the missing property name from the error. That pair goes into the repair message and the log; the keyword alone goes into the metric. The offending value goes nowhere.\n- Bean Validation on the bound record (`@NotNull`, `@Pattern`) is a useful second layer for business rules. It is not a substitute for schema validation, because binding has already dropped or coerced things by then.\n\n```java\n// Spring Boot 4 / Jackson 3 sketch using networknt 3.x\n@Bean\nSchemaRegistry llmSchemaRegistry() {\n return SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12);\n}\n\nValidationResult validate(String schemaId, JsonNode doc) {\n Schema schema = schemas.get(schemaId); // compiled once at startup from classpath\n List errors = schema.validate(doc);\n return errors.isEmpty()\n ? ValidationResult.ok()\n : ValidationResult.invalid(errors.stream()\n .map(e -> new SchemaViolation(String.valueOf(e.getInstanceLocation()), e.getKeyword()))\n .toList());\n}\n```\n\nTreat the sketch as shape only and check method names against the version in the build.\n\n## Bounded repair, then fail closed\n\nAt most one repair attempt per logical call, and only for outcomes repair can fix.\n\n- **Repairable:** `parse_error`, `schema_invalid`, `business_rule_invalid`. Re-ask once on the same target with the original messages, the model's previous output, and a short system-authored message listing the violations as `{path, keyword}` pairs (\"`/priority` must be one of p1, p2, p3, p4\"). Do not echo user content or field values in that message. Keep the same schema and the same mode.\n- **Truncated:** one retry with a higher output-token cap, only if the cap is still inside the route's token budget. Otherwise fail. Do not ask the model to \"continue\" a structured document and stitch the halves together.\n- **Not repairable:** `refused`, `filtered`, `unexpected_stop`, oversize, or a second failure of any kind. Return the typed failure.\n- The repair attempt counts against the route deadline and token budget (**llm-cost-latency-budget-guardrails**). It is not a routing fallback, and it does not move to another provider. Whether a provider 400 on the schema itself may fall back is the routing skill's `fallbackOnBadRequest` decision.\n- Never relax the schema, drop the strict flag, or switch to prompt-only JSON on the retry.\n- No local \"fixers\" that guess: no trimming to the last `}`, no regex quoting of keys, no defaulting a missing required field. A deterministic normalizer is allowed only for a documented, tested case (stripping a single Markdown code fence around otherwise valid JSON from a prompt-only target), and its use is counted.\n\nFail closed means the caller gets a typed error, not a partial record. For an HTTP API, problem+json with a stable code: `llm_output_invalid` (422 or 502, pick one per API and document it), `llm_output_refused`, `llm_output_truncated`. For an internal call, a sealed result type (`Valid | Invalid | Refused | Truncated | Filtered`) so the compiler forces every branch. Nothing downstream receives a default-constructed record.\n\n## Never evaluate model output\n\nStructured output is data. It is never code.\n\n- No `ScriptEngine`, SpEL, OGNL, MVEL, Groovy, JavaScript, or template evaluation of any field. No reflection on a class or method name the model supplied. No polymorphic Jackson typing (`@JsonTypeInfo` with class names, default typing) on these records.\n- A field that selects behavior is an enum mapped in a `switch` to code you wrote. A string is not a method name, a bean name, a URL, a file path, or a query fragment.\n- A field that ends up in SQL, a shell, a URL, HTML, or a log line is encoded or parameterized for that sink, as **llm-app-prompt-injection-guardrails** requires.\n\n## Tool-call arguments are untrusted input\n\nStrict tool calling guarantees the arguments match the tool's schema. It does not mean the caller is allowed to do what they describe.\n\n- The tool name must be on this route's allowlist. An unknown or disallowed name is rejected before argument parsing, even if the provider says it is valid.\n- Validate arguments against the server's copy of the tool schema, the same way as any structured output, then bind to a record.\n- Authorize as the end user (on-behalf-of or row-filtered access), not as the service. Every ID in the arguments is checked against what this caller may touch. Tenant and user come from the authenticated context, never from an argument.\n- Allowlist values that select targets: hosts, queues, table names, file roots, email domains. Bounded numbers for limits and amounts.\n- Side-effecting tools need an idempotency key from the server (not the model) and, where the action is high impact, a confirmation step. Loop limits and approval steps are in the prompt-injection skill.\n- A validation or authorization failure goes back to the model as a short tool error (\"argument `/account_id` not permitted\") so the loop can recover once, and it counts toward the same single repair limit.\n\n## Metrics and logs without payloads\n\nCount outcomes, not content.\n\n- `llm_structured_output_total`: counter. Labels: `route`, `schema` (name and version), `mode` (`native`, `json_mode`, `prompt_only`, `tool`), `outcome` (`valid`, `repaired`, `parse_error`, `schema_invalid`, `business_rule_invalid`, `refused`, `truncated`, `filtered`, `unexpected_stop`, `oversize`).\n- `llm_structured_output_violations_total`: counter. Labels: `schema`, `keyword` (`required`, `enum`, `additionalProperties`, `type`, `pattern`, ...). Use the keyword, not the instance path, so label cardinality stays fixed. Put the path in a log field if you need it.\n- `llm_tool_call_rejected_total`: counter. Labels: `route`, `tool`, `reason` (`unknown_tool`, `schema_invalid`, `not_authorized`, `not_allowlisted`).\n- Logs: request ID, route, schema version, mode, provider target, stop reason, outcome, violation `{path, keyword}` pairs, and whether repair ran. Not the completion, not the arguments, not the offending value, and not a hash of it. If a debug capture is truly needed, it goes through the redacted view from **llm-pii-redaction-guardrails** and stays off in shared environments.\n- Alert on a rise in `schema_invalid` or `refused` per schema version, and on any `unexpected_stop`. A jump after a model or alias change usually means the target lost native schema support.\n\n## Conformance fixtures in CI\n\nAdd schema conformance to the existing eval gate in **llm-eval-ci-regression-gate**. Do not build a second gate.\n\n- **Offline, deterministic (every PR).** A fixture directory per schema version with recorded or synthetic model outputs: valid documents, a missing required field, an extra property, a wrong enum, a null where not allowed, a duplicate key, a truncated object, a refusal response, a content-filter stop, a response with prose around the JSON, two tool calls where one was expected, and an unknown tool name. Each fixture asserts the outcome, the `{path, keyword}` list, and that nothing reached the consumer or the tool stub.\n- **Repair path.** A stub provider returns an invalid document, then a valid one. Assert exactly two provider calls, outcome `repaired`, and that the repair message lists keywords and paths but contains none of the fixture values. A second stub returns invalid twice: assert two calls, the typed failure, and no third call.\n- **Truncation and refusal.** The stub returns `finish_reason: length` with a half object, and a refusal. Assert no parse attempt, the right outcome, and no repair call for the refusal.\n- **Tool authz.** Valid arguments with another tenant's ID are rejected with `not_authorized`, and the tool stub sees zero calls.\n- **Schema and record agree.** A test generates or loads the schema and checks it against the Java record, and a test sends each schema to a strict-mode lint (or a recorded provider acceptance) so a rejected keyword is caught before deploy.\n- **Live conformance rate (scheduled or on prompt/model change).** Run the golden inputs against the real target and report the share of `valid` on first attempt, `repaired`, and failed, per schema version. The gate fails when first-attempt conformance drops below the agreed floor for that schema, or when `unexpected_stop` appears. Record the floor next to the schema version.\n\nFixtures are synthetic. No customer transcripts.\n\n## Workflow\n\n1. Inventory every place model output is parsed or a tool call is executed. Table: call site | schema (or none) | mode | stop reason checked? | validator? | retry policy | consumer.\n2. Write or generate versioned schemas, closed and fully required, with enums and an escape value.\n3. Turn on native schema mode or strict tools where the target supports it. Keep prompt-only targets explicit.\n4. Add the ordered checks: stop reason, extract, size, strict parse, validate, bind, business rules.\n5. Add the single repair attempt and the typed failure result. Remove unbounded loops and guessing fixers.\n6. Gate tool calls: allowlist, server-side schema, end-user authz, value allowlists.\n7. Add the counters and log fields. Check that no payload or value reaches a log, a label, or a span.\n8. Land the fixtures and wire the conformance rate into the eval gate before enabling a new schema version in production.\n\n## Tool-specific notes\n\n- **GitHub Copilot:** path-scoped `.github/instructions/llm-structured-output.instructions.md` with `applyTo` for `**/llm/**`, `**/*Schema*.java`, `**/*Tool*.java`, `**/gateway/**`, and `**/llm-schemas/**`. Put the check order, \"validate even in native mode\", and \"one repair, then fail closed\" at the top. Keep the procedure in an optional `.github/skills/llm-structured-output-guardrails/SKILL.md`. Ask for the inventory table before editing a parser.\n- **Claude Code:** `.claude/skills/llm-structured-output-guardrails/SKILL.md` holds the procedure. Add one `CLAUDE.md` fact: \"Model JSON and tool arguments are validated server-side against versioned schemas in `llm-schemas/` before use. One repair attempt, then a typed failure. Model output is never evaluated.\"\n- **Codex:** root `AGENTS.md` stays a short brief: where schemas live, the validator bean, the outcome enum, and the conformance test command. The procedure lives in `SKILL.md`, or in a nested `AGENTS.md` beside the gateway module when the repo already uses nested briefs. Do not paste this whole skill into `AGENTS.md`.\n\n## Anti-patterns\n\n- \"Return only JSON\" in the prompt as the only control\n- Trusting native schema mode and skipping server-side validation\n- Parsing before checking the stop reason, so a refusal or a truncated object reaches the parser\n- Regex-extracting the first `{...}` from prose, or closing braces on a truncated document\n- `additionalProperties` left open, optional fields with silent Jackson defaults, or free-form string fields for decisions\n- Deleting a schema rule the provider rejected instead of enforcing it in the validator\n- Unbounded \"try again until it parses\" loops, or a retry that relaxes the schema or drops strict mode\n- `ScriptEngine`, SpEL, reflection, or polymorphic typing driven by model output\n- Executing a tool because the arguments are schema-valid, without the allowlist and end-user authorization\n- Tenant or user IDs taken from tool arguments\n- Logging the completion, the arguments, or the failing value to debug a validation error\n- Instance paths or values as metric labels\n- A schema change with no version bump and no fixtures\n\n## Done when\n\n- [ ] Every parse site and tool executor is in the inventory table with its schema version and mode\n- [ ] Schemas are versioned files in the repo, closed (`additionalProperties: false`), fully required with nullable instead of optional, enums with an escape value, no free-form unions\n- [ ] Native schema mode or strict tools are used where the target supports them, and rules the provider rejects are enforced server-side\n- [ ] Stop reason is checked before parsing; refusal, truncation, filter, and unknown stops are typed outcomes\n- [ ] A JSON Schema validator compiled at startup validates every document, including in native mode, then business rules run on the bound record\n- [ ] At most one repair attempt, inside the route budget, with `{path, keyword}` feedback and no values; then a typed failure\n- [ ] Model output is never evaluated or used for reflection or polymorphic typing\n- [ ] Tool calls pass a name allowlist, server-side schema validation, end-user authorization, and value allowlists before execution\n- [ ] Counters by route, schema version, mode, outcome, and keyword; no payloads or values in logs, labels, or spans\n- [ ] Conformance fixtures run on every PR, and the first-attempt conformance rate per schema version is a gate in the existing eval pipeline\n\n## Copy-ready SKILL.md stub\n\n```markdown\n---\nname: llm-structured-output-guardrails\ndescription: Use when a Java or Spring service or LLM gateway parses JSON from a model or executes tool-call arguments. Covers provider-native schema mode vs JSON mode vs prompt-only, closed and versioned JSON Schemas (required fields, enums with an escape value, additionalProperties false, no free-form unions), checking the stop reason before parsing (refusal, truncation, filter), server-side validation with a JSON Schema validator such as networknt, one bounded repair then fail closed, never evaluating output, tool arguments as untrusted input (allowlist, end-user authz), outcome counters without payloads, and schema-conformance fixtures in CI.\n---\n\nFollow LLM Structured Output Guardrails: ask the provider for native schema mode or strict tools where supported, and still validate every document on the server. Keep schemas versioned in the repo, closed, fully required (nullable instead of optional), with enums and an explicit escape value. Check the stop reason before parsing; refusal, truncation, and filter stops are typed failures, not data. Parse strictly, validate with a compiled JSON Schema validator, bind, then check business rules. Allow one repair attempt with path and keyword feedback and no values, then fail closed. Never evaluate model output. Treat tool-call arguments as untrusted: allowlist the tool, validate, authorize as the end user. Count outcomes by schema version and keyword, never log payloads, and gate first-attempt conformance in CI.\n```\n" + }, + { + "id": "llm-gateway-caching-guardrails", + "title": "LLM Gateway Caching Guardrails", + "whenToUse": "Adding or reviewing caching in an LLM gateway or Java/Spring Boot service — provider prompt caching first, then an opt-in exact response cache, and a semantic cache only where it is safe — with keys and partitions scoped by tenant, auth scope, model, prompt and corpus version, eligibility rules for what may be stored, per-route thresholds from labeled near-miss pairs, invalidation by version and erasure, cache status headers, and CI tests.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "llm", + "caching", + "semantic-cache", + "prompt-caching", + "gateway", + "spring-boot" + ], + "formatNotes": "All three. Copilot: path-scoped `.github/instructions/llm-caching.instructions.md` with applyTo for `**/gateway/**`, `**/cache/**`, `**/llm/**`, and `**/prompts/**`. Optional on-demand procedure at `.github/skills/llm-gateway-caching-guardrails/SKILL.md`. Claude Code: `.claude/skills/llm-gateway-caching-guardrails/SKILL.md` plus a CLAUDE.md fact that response caching is opt-in per route and semantic lookups never cross tenant, scope, model, prompt, or corpus partitions. Codex: a short \"LLM caching\" brief in root `AGENTS.md` (cache config location, key builder class, eligible routes, near-miss test command) while the procedure stays in SKILL.md. Pair with llm-cost-latency-budget-guardrails for pricing cached tokens and hits, llm-gateway-routing-fallback-guardrails for capability flags, llm-pii-redaction-guardrails for what is stored and embedded, llm-structured-output-guardrails for validating a response before it may be cached, rag-retrieval-eval-guardrails for corpus versions, llm-eval-ci-regression-gate for the near-miss gate, and spring-boot-cache-redis-guardrails for plain Redis hygiene. This skill owns the cache tiers, keys, partitions, eligibility, thresholds, and invalidation.", + "body": "# Skill: LLM Gateway Caching Guardrails\n\n## Goal\n\nAn LLM gateway or a Java/Spring Boot service reuses work it has already paid for without ever serving one caller's answer to another, serving a stale answer after the model, prompt, or data changed, or serving the answer to a different question that happened to sound similar.\n\nThis skill owns three caches and the rules that keep them honest:\n\n1. **Provider prompt caching** (prefix caching done by the provider). Cheap input tokens on repeated prefixes. No answer is reused.\n2. **Exact response cache** in the gateway. The same normalized request returns the stored response.\n3. **Semantic response cache** in the gateway. A request that is close enough in embedding space returns a stored response.\n\nThey carry very different risk. Roll them out in that order and stop at the level that pays for itself.\n\nToken budgets and price tables stay in **llm-cost-latency-budget-guardrails**; this skill only reports cache savings into them. Target selection, fallback, and capability flags stay in **llm-gateway-routing-fallback-guardrails**. Redaction before anything is stored or embedded stays in **llm-pii-redaction-guardrails**. Schema validation of a response before it may be cached stays in **llm-structured-output-guardrails**. Retrieval quality and corpus versions stay in **rag-retrieval-eval-guardrails**. The CI gate that reads the false-hit rate stays in **llm-eval-ci-regression-gate**. Plain Spring Cache and Redis hygiene (serializers, TTLs, eviction, key prefixes) stays in **spring-boot-cache-redis-guardrails**.\n\nA cache hit is the gateway answering on the model's behalf. Treat it with the same care as a model response.\n\n## When to apply\n\n- Adding prompt caching, a response cache, or a semantic cache to a gateway, Spring AI or LangChain4j app, or an API Management / proxy policy\n- Long, stable system prompts, tool lists, or reference documents sent on every request\n- FAQ-style or classification traffic with many repeated questions\n- A review that finds a cache key built from the user message alone, a single global semantic index, no TTL, or a similarity threshold copied from a blog post\n- Cost reports where cached tokens or cache hits are not visible\n\n## Level 1: provider prompt caching\n\nPrefix caching lowers input cost and time to first token on repeated prefixes. It never returns a stored answer, so it is the safe first step.\n\n- **Order the prompt for it.** Static content first: system instructions, tool definitions, schemas, few-shot examples, long reference text. Per-request content last: user message, retrieved chunks, timestamps, request IDs. One volatile line at the top (a date, a user name) breaks the prefix for everything after it.\n- **Keep the prefix byte-stable.** Deterministic JSON key order for tool and schema definitions, no reordered tool lists, no whitespace changes between releases. A prompt template change is a new prompt version and is expected to miss once.\n- **Turn it on per provider from capability config.** Some providers cache automatically above a minimum prefix length; others need explicit markers (for example Anthropic `cache_control` breakpoints, or Bedrock cache checkpoints). Minimum lengths, lifetimes, write premiums, and read discounts differ by provider and model and change often. Keep them in config with a \"checked on\" date and the doc link, not in code or comments.\n- **Write premiums are real.** Where a cache write costs more than a normal input token, only mark prefixes that repeat within the lifetime. A marker on a prompt that never repeats costs more, not less. Longer lifetimes cost more to write; pick them from measured reuse, not by default.\n- **Read the usage fields.** Record cached-read and cache-write token counts from every response (provider names differ, for example `cached_tokens`, `cache_read_input_tokens`, `cache_creation_input_tokens`) and pass them to the cost ledger in **llm-cost-latency-budget-guardrails**, which prices them. A prefix that should hit but reports zero cached tokens is a bug to investigate (volatile prefix, below the minimum, expired, or the router dropped the marker).\n- **Isolation.** Provider prompt caches are scoped by the provider (typically per organization or workspace). Check the provider's documented scope before routing several customers' traffic through one key, and use any per-customer cache key the provider offers for accounting.\n\n## Level 2: exact response cache\n\nReturn the stored response only when the request is the same request.\n\n**Cache key.** A SHA-256 over a canonical serialization of everything that changes the answer:\n\n- tenant, and the caller's authorization scope (role set, data-access groups, row filter version) when the answer depends on what the caller may see\n- route and target model (resolved deployment and version, not an alias)\n- prompt template ID and version, and tool definitions version\n- the full message list after redaction, normalized (Unicode NFC, trimmed whitespace) but not paraphrased\n- generation parameters that matter: `temperature`, `top_p`, `max_tokens`, response format and schema version, tool choice, seed\n- retrieval corpus or index version for RAG routes, plus the IDs of the retrieved chunks when retrieval runs before the lookup\n\nPrefix the stored key with a cache version (`llmc:v3:`) so a format change is a clean break. Never store the raw prompt in the key.\n\n**What may be cached:**\n\n- Only routes that opt in, in config, with a reason. Default is off.\n- Only successful, complete responses: normal stop reason, schema-valid where a schema applies, not refused, not filtered, not truncated.\n- Not responses that contain tool calls or that led to side effects. Not streaming partials.\n- Not responses whose answer depends on time, on live data the key does not capture, or on the individual user's history, unless the key carries that dependency.\n- Deterministic or near-deterministic routes (low temperature, classification, extraction). Creative routes gain little and surprise users when the \"random\" answer repeats.\n\n**Storage.** Store the redacted response body, the key fields as metadata (not the prompt), model, prompt version, created time, TTL, and the request ID that produced it. Encrypt at rest as the data classification requires. Every entry has a TTL. Keep it short for anything user-specific and longer only for generic content.\n\n## Level 3: semantic response cache\n\nA semantic cache answers a different request with a stored response because two embeddings were close. That is a correctness decision, not an optimization. Add it only after Level 2 is live and measured.\n\n**Hard partition first, similarity second.** The vector search runs only inside a partition that matches exactly on: tenant, authorization scope, route, target model and version, prompt template version, tool definitions version, embedding model and version, response schema version, and corpus or index version for RAG. Similarity never crosses those boundaries. Two users with different permissions do not share an entry even for the identical question.\n\n**What gets embedded.** The normalized, redacted user question, plus any context that changes the answer. If the system prompt, retrieved context, or conversation history changes the answer and is not in the embedding or the partition, the route is not eligible. Multi-turn conversations are usually not eligible past the first turn; cap by message count or skip.\n\n**Threshold.**\n\n- There is no universal number. It depends on the embedding model, the domain, the language, and the cost of a wrong answer. Published values from one setup do not transfer.\n- Know which direction your store measures. Some return a similarity (higher is closer), others a distance (lower is closer), and some policies call a distance a \"score\". Write the direction next to the value in config and test it with a known pair.\n- Build a labeled set of question pairs from real (redacted) traffic: pairs that should share an answer and near-miss pairs that must not (\"reset my password\" vs \"reset my API key\", \"cancel\" vs \"pause\", \"monthly\" vs \"annual\", negations, different IDs or amounts). Pick the threshold from the false-hit rate the route can tolerate, then check the hit rate.\n- Set a stricter threshold, or disable the semantic tier, for routes where a wrong answer is expensive: money, policy, eligibility, health, security, or anything with an account-specific value.\n- Requests carrying identifiers, amounts, dates, or code skip the semantic tier and go to Level 2 only. A one-character difference in an ID is a different question.\n\n**Guarded serve.** On a candidate hit, also check: entry not expired or invalidated, same partition (re-verify, do not trust the index filter alone), and the stored entry passed the same validation as a fresh response. Optionally run a cheap verifier (a small model or rules) on borderline scores, or use near hits only as a hint, never as the answer.\n\n**Latency.** Every semantic lookup pays for an embedding and a vector query. Put a timeout on both; on timeout or cache error, go to the model. Measure that the hit rate pays for the extra latency on misses.\n\n## Invalidation\n\n- **By version, not by hunting.** A new model version, prompt template, tool definition, schema, embedding model, or corpus version changes the partition or the key, so old entries are never read again and expire by TTL.\n- **By event.** When source data changes (a policy page, a product price, a document deleted), invalidate entries tagged with that source. Store source tags on RAG entries for this.\n- **By request.** A user deletion or data-erasure request removes every entry in that user's or tenant's partition. Test it.\n- **Kill switch.** One config flag per route and tier turns caching off without a deploy, and a purge command clears a partition.\n\n## Response semantics\n\n- Mark cached responses to the caller: a header such as `X-Cache: HIT-EXACT | HIT-SEMANTIC | MISS | BYPASS`, and the original creation time. Do not pretend a cached answer is fresh.\n- Honor a bypass from trusted callers (`Cache-Control: no-cache` from an internal client, or a per-route flag). Do not let an end user force a write into a shared partition.\n- A cache hit still goes through output guardrails that depend on the current caller (authorization re-check on referenced records, redaction for the current audience).\n- Usage and billing: a hit consumes no model tokens. Record it as a hit with zero model cost and the embedding cost for semantic lookups, so cost reports stay true.\n\n## Security\n\n- **Poisoning.** A shared partition can be poisoned by one caller who gets a bad or injected answer stored. Do not write to shared partitions from untrusted or anonymous traffic, store only responses that passed every output check, and prefer pre-seeded, reviewed entries for shared FAQ caches.\n- **Leakage.** No cross-tenant or cross-scope reads, ever. The partition key comes from the authenticated context, not from request fields.\n- **Data at rest.** The cache is a copy of prompts and answers. It follows the same retention, residency, and encryption rules as the conversation logs. Redact before embedding and before storing (**llm-pii-redaction-guardrails**).\n- **Timing.** Hit-vs-miss latency reveals whether someone asked a similar question. In a shared partition that is acceptable only for public content.\n\n## Metrics\n\n- `llm_cache_requests_total`: labels `route`, `tier` (`exact`, `semantic`), `result` (`hit`, `miss`, `bypass`, `ineligible`, `error`)\n- `llm_cache_semantic_score`: histogram of best candidate scores for hits and misses, per route\n- `llm_prompt_cache_tokens_total`: labels `route`, `provider`, `kind` (`read`, `write`)\n- `llm_cache_false_hit_total`: from user feedback, re-asks within a short window, or offline audit; labels `route`, `tier`\n- `llm_cache_saved_cost`: computed by the cost ledger, not here\n\nNo prompt text, answer text, or tenant name in labels. Log the request ID, route, tier, result, score, and the matched entry's request ID.\n\n## Tests and CI\n\n- **Key tests.** Changing each key component (tenant, scope, model, prompt version, schema version, temperature, corpus version) produces a miss. Identical requests from two tenants never share an entry.\n- **Eligibility.** Refused, truncated, filtered, schema-invalid, tool-call, and streaming-partial responses are never stored. Ineligible routes never read or write.\n- **Semantic near-miss set.** A labeled pair file per semantic route runs in CI against the chosen embedding model and threshold. The build fails when any must-not-match pair would hit, or when the false-hit rate on the labeled set exceeds the route's limit. Wire it into the existing eval gate in **llm-eval-ci-regression-gate**.\n- **Invalidation.** Bumping a prompt version or corpus version makes old entries unreachable; an erasure request leaves zero entries in the partition.\n- **Failure.** Cache store down or slow: requests succeed through the model within the route deadline.\n- **Prompt caching.** A fixture asserts that the rendered prompt's static prefix is byte-identical across two requests with different user messages.\n\n## Workflow\n\n1. Inventory routes: route | deterministic? | user-specific? | RAG? | repeat rate | wrong-answer cost | proposed tier.\n2. Reorder prompts for prefix caching and record cached tokens. Ship and measure.\n3. Add the exact cache to eligible routes with the full key, eligibility rules, TTLs, and the `X-Cache` header.\n4. Only for routes with high repeat rates and tolerable wrong-answer cost, build the labeled pair set, choose a threshold, and add the semantic tier with hard partitions.\n5. Add invalidation by version, source tag, and erasure, plus the kill switch.\n6. Add metrics and CI tests. Review false hits weekly for the first month after enabling a semantic route.\n\n## Tool-specific notes\n\n- **GitHub Copilot:** path-scoped `.github/instructions/llm-caching.instructions.md` with `applyTo` for `**/gateway/**`, `**/cache/**`, `**/llm/**`, and `**/prompts/**`. Put \"partition before similarity\", the eligibility list, and \"version bump invalidates\" at the top. Optional procedure in `.github/skills/llm-gateway-caching-guardrails/SKILL.md`.\n- **Claude Code:** `.claude/skills/llm-gateway-caching-guardrails/SKILL.md` holds the procedure. Add one `CLAUDE.md` fact: \"LLM response caching is opt-in per route. Keys include tenant, auth scope, model version, prompt version, and corpus version. Semantic cache never crosses those partitions.\"\n- **Codex:** root `AGENTS.md` gets a short brief: where cache config lives, the key builder class, eligible routes, and the near-miss test command. The procedure stays in `SKILL.md`.\n\n## Anti-patterns\n\n- A cache key built from the user message alone, or one global semantic index for all tenants\n- Similarity threshold copied from another system, or similarity and distance confused\n- Caching refused, truncated, filtered, schema-invalid, or tool-call responses\n- No TTL, or invalidation by \"flush everything\" only\n- Timestamps or request IDs at the top of the prompt, killing prefix caching\n- Cache markers on prompts that never repeat, paying write premiums for nothing\n- Semantic cache on account-specific, money, or policy answers\n- Shared partitions written by anonymous traffic\n- Raw prompts or answers in keys, labels, or logs\n- Cached answers served without telling the caller\n\n## Done when\n\n- [ ] Every route has a documented tier (none, prompt cache only, exact, semantic) and a reason\n- [ ] Prompts put static content first; cached-read and write tokens are recorded and priced by the cost ledger\n- [ ] Exact cache keys include tenant, auth scope, resolved model, prompt and tool versions, normalized redacted messages, generation parameters, and corpus version\n- [ ] Only complete, valid, non-tool, non-refused responses are stored, with a TTL and redacted content\n- [ ] Semantic lookups run inside exact-match partitions, with a per-route threshold chosen from a labeled near-miss set and the measure direction documented\n- [ ] Version bumps, source-tag events, and erasure requests invalidate entries; a kill switch exists per route and tier\n- [ ] Responses carry a cache status header; hits are recorded with zero model cost\n- [ ] Key, eligibility, near-miss, invalidation, and outage tests run in CI\n\n## Copy-ready SKILL.md stub\n\n```markdown\n---\nname: llm-gateway-caching-guardrails\ndescription: Use when adding or reviewing provider prompt caching, an exact response cache, or a semantic cache in an LLM gateway or Java/Spring service. Covers prompt ordering for prefix caching and recording cached tokens, cache keys that include tenant, auth scope, resolved model, prompt and tool versions, generation parameters and corpus version, which responses may be stored, hard partitions before any similarity search, per-route thresholds from a labeled near-miss set, invalidation by version, source tag and erasure, cache status headers, poisoning and leakage controls, metrics, and CI tests.\n---\n\nFollow LLM Gateway Caching Guardrails: roll out provider prompt caching first (static content first, record cached tokens), then an opt-in exact response cache, and a semantic cache only where repeat rate is high and a wrong answer is cheap. Keys and partitions include tenant, authorization scope, resolved model, prompt and tool versions, schema version, generation parameters, embedding model, and corpus version; similarity never crosses them. Store only complete, valid, non-tool, non-refused, redacted responses with a TTL. Choose each semantic threshold from a labeled near-miss set and document whether the store measures similarity or distance. Invalidate by version bump, source tag, and erasure request, keep a kill switch, mark hits to the caller, and test keys, eligibility, near misses, invalidation, and cache outages in CI.\n```\n" } ] }