Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions promptbook/prompts.json
Original file line number Diff line number Diff line change
Expand Up @@ -1102,6 +1102,26 @@
],
"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"
},
{
"id": "harden-llm-streaming-responses",
"title": "Harden Streaming (SSE) Responses on LLM Routes",
"whenToUse": "Fix LLM streaming that buffers into one late burst, keeps billing after the user leaves, or hides failures as finished answers — event contract with terminal frames, before-first-byte checks and fallback, no retry after content, end-to-end cancellation, three deadlines plus heartbeats, ingress and compression settings, output-check modes, tool-call assembly, final or estimated usage, metrics, shutdown drain, and fake-upstream tests.",
"tools": [
"copilot",
"claude-code",
"codex"
],
"tags": [
"llm",
"streaming",
"sse",
"gateway",
"spring-boot",
"cancellation"
],
"formatNotes": "All three. Point the tool at the stream relay or chat controller, the model client, the streaming Ingress or edge config, application config, and the test folder. Copilot: llm-streaming path instructions plus those files in agent mode (or save the prompt as `.github/prompts/harden-llm-streaming-responses.prompt.md`). Claude Code: the llm-streaming-response-guardrails skill plus the relay and Ingress files. Codex: the AGENTS.md LLM streaming section, then the diff. Leave routing policy, price tables, redaction rules, schema validation, and caching to their own skills.",
"body": "Task: Make streaming (SSE) responses on the LLM routes I specify reliable and cheap. Callers must see tokens as they are generated, a client that leaves must stop the upstream model call, a failure must never look like a successful answer, and every stream must be accounted for in usage. 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; WebFlux | Spring MVC with SseEmitter | Spring AI | LangChain4j | plain WebClient/HttpClient)\n- Providers and targets: {{PROVIDERS}} (Azure OpenAI, OpenAI, Anthropic, Amazon Bedrock, OpenRouter, other OpenAI-compatible) and each one's stream format and usage option\n- Streaming routes: {{ROUTES}} (route → client type → output checks needed → observed TTFT p99 → max duration)\n- Wire format to clients: {{WIRE_FORMAT}} (OpenAI-compatible chat chunks | provider-native | custom events)\n- Edge path: {{EDGE}} (ingress-nginx | Gateway API implementation | Application Gateway | API Management | mesh | CDN) and the manifest location\n- Output checks on streams: {{OUTPUT_CHECKS}} (PII redaction, policy filter, schema validation, none)\n- Observability and cost: {{OBSERVABILITY}} (Micrometer | OpenTelemetry | both) and the cost ledger that prices tokens\n\nRequirements:\n\n1. Inventory\n - Table: route | stack (WebFlux or MVC) | providers | forwards incrementally? | cancels upstream on disconnect? | terminal frame on every exit? | retries after first byte? | output-check mode | usage source\n - Flag any route that collects the whole upstream response before forwarding, drains the upstream after the client leaves, or closes without a finish reason or error frame\n\n2. Event contract\n - Headers: `Content-Type: text/event-stream`, `Cache-Control: no-cache`, `X-Accel-Buffering: no`, request ID header; no `Content-Length`, no compression\n - Order: content chunks, finish-reason chunk, usage chunk (empty `choices`), `data: [DONE]`\n - Every exit path (clean stop, upstream error, deadline, policy block, shutdown) ends with a finish reason or an in-band error frame such as `{\"error\":{\"type\":...,\"code\":...,\"message\":...,\"request_id\":...}}` followed by `[DONE]`. No stack traces, keys, or raw upstream bodies\n\n3. Before the first byte\n - Auth, authorization, budget check, validation, input redaction, and target selection run before any bytes are written\n - Wait for the first upstream chunk before committing the 200; upstream errors and connect timeouts here return a normal HTTP error and may use routing fallback\n - Race that wait against client disconnect; on disconnect cancel upstream and record `client_cancelled`\n - Per-route time-to-first-token deadline in config\n\n4. After the first byte\n - No retry and no fallback once content was sent; send an error frame and end\n - Client disconnects never count as provider failures and never trip circuit breakers\n\n5. Cancellation\n - Propagate cancellation from the inbound request to the upstream call. WebFlux: build the response `Flux` from the upstream body so cancel disposes the connection. MVC: `SseEmitter` `onCompletion`/`onTimeout`/`onError` cancel the upstream subscription, and a send `IOException` is a disconnect\n - Close the upstream connection, never drain it\n - Outcomes: `completed`, `client_cancelled`, `upstream_error`, `deadline_exceeded`, `policy_blocked`, `shutdown`\n\n6. Deadlines, heartbeats, buffers\n - Three timers per route in config: time to first token, inter-chunk idle, total stream. Choose values from observed data and write the source next to each value\n - SSE comment heartbeat (`: ping`) at an interval shorter than the smallest idle timeout on the path; heartbeats do not reset the inter-chunk idle timer\n - Bounded per-stream buffer; a slow reader that fills it gets an error frame. No full-text accumulation for logging\n\n7. Edge and server settings ({{EDGE}}, streaming paths only)\n - ingress-nginx: separate Ingress for streaming paths with `proxy-buffering: \"off\"` and `proxy-read-timeout` / `proxy-send-timeout` above the total stream deadline. Other edges: the equivalent buffering and timeout settings from their docs\n - Exclude `text/event-stream` from Spring and proxy compression\n - MVC: `spring.mvc.async.request-timeout` at least the total stream deadline. Note if a platform-thread pool limits concurrent streams\n\n8. Output checks on streams ({{OUTPUT_CHECKS}})\n - Declare per route: pass-through (audit on final text), windowed (hold back a trailing window at least as long as the longest redaction pattern), or buffered (release nothing until checks pass; heartbeats only)\n - Mid-stream policy block ends with a `policy_blocked` error frame\n - Routes that need schema-valid JSON do not stream raw partial JSON to clients that cannot handle it\n\n9. Tool calls\n - Assemble fragmented tool-call arguments per index; parse and validate only after the tool-call finish reason; never execute from a partial string\n\n10. Usage, metrics, logs ({{OBSERVABILITY}})\n - Request usage on streams where the provider makes it optional (for example `stream_options: {\"include_usage\": true}`)\n - Early end without a usage event: estimate output tokens from the text received with the ledger's tokenizer, mark `usage_source=estimated`, never record zero. Pass counts to the cost ledger; do not price here\n - Metrics: `llm_stream_requests_total` (`route`, `target`, `outcome`), `llm_stream_ttft_seconds`, `llm_stream_duration_seconds`, `llm_stream_inter_chunk_gap_seconds`, `llm_stream_active`, `llm_stream_tokens_after_cancel_total`\n - Logs: request ID, route, target, outcome, TTFT, duration, chunk count, tokens and source, early-end reason. No prompt or completion text\n\n11. Shutdown\n - On SIGTERM fail readiness, drain active streams up to a configured limit, then end the rest with a `shutdown` error frame and `[DONE]`. `terminationGracePeriodSeconds` covers preStop plus drain\n\n12. Tests (fake streaming upstream: WireMock, MockWebServer, or a Netty stub; no real provider calls)\n - Contract and headers; cancel mid-stream closes upstream within a bound; cancel before first token cancels upstream\n - Error before first byte returns an HTTP error and allows fallback; error after first byte sends an error frame and calls no second target\n - Idle stall hits `deadline_exceeded`; quiet upstream produces heartbeats\n - Early end records estimated usage; secret split across chunks is redacted in windowed mode\n - Fragmented tool-call arguments parse only after the finish reason; shutdown sends a `shutdown` frame\n - A smoke script against the deployed edge with a slow fake stream shows chunks arriving incrementally\n\nConstraints:\n- Minimal diff. Reuse the existing HTTP client, Reactor or MVC style, and metrics registry; no new streaming framework.\n- Do not change non-streaming routes or global ingress settings.\n- Do not lengthen a deadline, drop a terminal frame, or disable a test to make CI pass.\n- Leave routing and fallback policy, price tables, redaction rules, schema validation, caching, and eval gates to their existing skills; call their hooks.\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 with the gaps found\n2. Stream relay diff (contract, terminal frames, before-first-byte logic, cancellation)\n3. Deadlines, heartbeat, buffer, and output-check mode config\n4. Edge, compression, and shutdown changes\n5. Usage and metrics changes, and the tests added with what each asserts\n\nStart from {{APP_PATH}}. Fix cancellation and terminal frames first, then deadlines and the edge, then usage and output checks.\n"
}
]
}
Loading
Loading