From 68bac5dd2f5c25fff3ffb7db57abf091621229fd Mon Sep 17 00:00:00 2001 From: Ramkumar Ethiraj <64294490+rmkr-dev@users.noreply.github.com> Date: Sun, 15 Nov 2026 05:13:40 +0000 Subject: [PATCH 1/2] Add LLM model and prompt rollout guardrails skill --- skillbook/skills.json | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/skillbook/skills.json b/skillbook/skills.json index 165691b..fa317b7 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -1160,6 +1160,26 @@ ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/llm-tracing.instructions.md` with applyTo for `**/gateway/**`, `**/llm/**`, `**/ai/**`, `**/observability/**`, and `**/otel-collector*.yaml`. Optional on-demand procedure at `.github/skills/llm-tracing-observability-guardrails/SKILL.md`. Claude Code: `.claude/skills/llm-tracing-observability-guardrails/SKILL.md` plus a CLAUDE.md fact that GenAI attribute names live in one constants class and prompt or completion text never goes into telemetry by default. Codex: a short \"LLM tracing\" brief in root `AGENTS.md` (constants class path, Collector config path, telemetry test command); the procedure can live in `.agents/skills/llm-tracing-observability-guardrails/SKILL.md`. Pair with otel-aks-observability for the Collector on AKS, llm-cost-latency-budget-guardrails for budgets and prices, llm-pii-redaction-guardrails for the redaction hook used by opt-in capture, llm-streaming-response-guardrails for first-token timing, llm-gateway-routing-fallback-guardrails for attempt and fallback semantics, and spring-boot-structured-logging-guardrails for trace IDs in logs. This skill owns the span tree, GenAI names, content capture policy, propagation, sampling, and telemetry tests.", "body": "# Skill: LLM Tracing and Observability Guardrails\n\n## Goal\n\nEvery LLM call, retrieval, tool call, and agent step in a Java/Spring Boot service or gateway shows up as one connected OpenTelemetry trace that an on-call engineer can read without seeing anyone's prompt. Spans and metrics use the OpenTelemetry GenAI semantic conventions, so Datadog, Azure Monitor, Grafana Tempo, or any OTLP backend understands them. Prompt and completion text stays out of telemetry unless a named, time-boxed, redacted opt-in turns it on.\n\nTypical failures this skill prevents:\n\n1. **Broken traces.** The gateway starts a new trace for each upstream call, so a slow answer cannot be tied to the request, the retrieval, or the retry that caused it.\n2. **Prompts in telemetry.** A framework logs full prompts and completions into span attributes or logs by default, and customer data now sits in a vendor backend with a different retention policy.\n3. **Cardinality blow-ups.** User IDs, conversation IDs, or prompt hashes used as metric labels.\n4. **Wrong numbers.** Token counts estimated when the provider returned usage, retries counted as separate user requests, streaming latency measured to the first byte of headers instead of the first token.\n5. **Silent renames.** GenAI conventions are still in Development status, attribute names change between versions, and dashboards quietly go empty after a library upgrade.\n\nToken budgets and price tables stay in **llm-cost-latency-budget-guardrails**. General AKS OpenTelemetry Collector setup stays in **otel-aks-observability**. Micrometer registry and Prometheus wiring stay in **spring-boot-micrometer-prometheus-guardrails**. Log format and MDC stay in **spring-boot-structured-logging-guardrails**. What counts as sensitive and how to redact it stays in **llm-pii-redaction-guardrails**. Streaming deadlines and terminal frames stay in **llm-streaming-response-guardrails**. Eval scoring stays in **llm-eval-ci-regression-gate** and **rag-retrieval-eval-guardrails**. This skill owns the span tree, GenAI attribute and metric names, content capture policy, context propagation, sampling, and the telemetry tests.\n\n## When to apply\n\n- Adding or reviewing tracing in an LLM gateway, RAG service, agent runtime, or MCP tool server\n- Adopting Spring AI or LangChain4j observability, or the OpenTelemetry Java agent, on a service that calls models\n- Moving LLM telemetry from a vendor-specific SDK to OTLP\n- A review finds prompts or completions in spans or logs, user IDs in metric labels, or one trace per upstream call\n- Upgrading OpenTelemetry instrumentation or the semantic conventions version\n\n## Span tree\n\nOne inbound request is one trace. A typical gateway or RAG request looks like this:\n\n```\nPOST /v1/chat/completions SERVER (http.route, tenant, gateway route)\n├── retrieval / vector search CLIENT (index alias, top_k, result count)\n├── chat {model} CLIENT attempt 1 → primary deployment (error.type=429)\n├── chat {model} CLIENT attempt 2 → fallback deployment (ok)\n│ └── execute_tool {tool} INTERNAL (tool name, call id, outcome)\n└── eval hook / guardrail checks INTERNAL (check name, verdict)\n```\n\n- One client span per **attempt**, so retries and fallbacks are visible; mark the attempt number and the routing reason. Usage metrics count once per billable attempt.\n- Agents: `invoke_agent {agent}` wraps the loop; each model turn is a `chat` span and each tool run an `execute_tool` span beneath it.\n- Span kind CLIENT for remote model calls, INTERNAL for in-process tools and checks. Span status ERROR only for real failures, with `error.type` set (HTTP status class, timeout, provider error code). A content-filter refusal is a result, not a span error; record it as a finish reason.\n\n## Attributes (GenAI semantic conventions)\n\nUse the attribute names from the pinned semantic conventions version, for example:\n\n- `gen_ai.operation.name` (`chat`, `embeddings`, `execute_tool`, `invoke_agent`)\n- `gen_ai.provider.name`, `gen_ai.request.model`, `gen_ai.response.model`\n- `gen_ai.request.max_tokens`, `gen_ai.request.temperature`, and other request parameters you actually send\n- `gen_ai.response.id`, `gen_ai.response.finish_reasons`\n- `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens` from the provider's usage block, not an estimate; mark estimates explicitly when a stream ends without usage\n- `gen_ai.tool.name`, `gen_ai.tool.call.id`, `gen_ai.agent.name`, `gen_ai.conversation.id` (span attribute only, never a metric label)\n- `server.address`, `server.port`, `error.type`\n\nRules:\n\n- **Pin the conventions version** and keep every GenAI attribute name in one constants class or config. A rename is then one diff, plus a dashboard update in the same PR. If the instrumentation library supports a stability opt-in setting for GenAI conventions, set it explicitly instead of taking the default.\n- Gateway-specific facts (route name, tenant, deployment, fallback reason, cache hit, budget decision) go in a short custom namespace such as `llm.gateway.*`, never squatted under `gen_ai.*`.\n- Never put API keys, bearer tokens, full URLs with query strings, or raw headers on spans.\n\n## Content capture policy\n\n- **Off by default.** No `gen_ai.input.messages`, `gen_ai.output.messages`, `gen_ai.system_instructions`, tool arguments, tool results, or retrieved chunk text in spans, span events, or logs.\n- Turn off framework defaults that log prompts or completions (Spring AI, LangChain4j, HTTP client wire logging) and assert that in a test.\n- Opt-in only per environment or per tenant, behind a named flag, time-boxed, and routed through the redaction hook before export. Prefer exporting content to a separate store with its own retention and access control, referenced from the span by an ID.\n- Record content **shape** instead: message count, input and output token counts, tool count, chunk IDs and scores (IDs, not text), output schema validation result.\n\n## Metrics\n\n- Use the GenAI metric names from the pinned version: token usage histogram (`gen_ai.client.token.usage` with `gen_ai.token.type`) and the duration histograms for inference, embeddings, tool and agent operations. Newer versions split the generic operation duration into per-operation metrics; follow whichever the pinned version defines.\n- For streaming, record time to first token and time per output token separately from total duration.\n- Labels: operation, provider, request model, response model, route, outcome or `error.type`, token type. Never user ID, conversation ID, prompt hash, or response ID. Keep tenant as a label only when the tenant count is small and bounded.\n- Micrometer Observation is fine: one Observation per operation produces both the span and the timer. Check the exported names match the conventions, or add a convention class that maps them.\n\n## Context propagation\n\n- W3C `traceparent` and `tracestate` in and out. The gateway continues the caller's trace and propagates to the provider call.\n- Context survives async hops: reactive pipelines, virtual threads, `@Async` executors, streaming callbacks, and message queues (inject into message headers and link consumer spans).\n- Baggage carries only non-sensitive, low-cardinality keys (tenant, route); strip inbound baggage you do not trust before it reaches the provider.\n- Logs carry `trace_id` and `span_id` via MDC so a log line jumps to its trace.\n\n## Sampling and export\n\n- Head sampling in the SDK at a modest rate, plus tail sampling in the Collector that keeps every error, every fallback, every guardrail block, and slow requests above the latency SLO.\n- Export over OTLP to the Collector, not straight from the app to a vendor; the Collector owns batching, retries, attribute deletion as a last line of defence, and routing.\n- Exporter failure never fails a request; bounded queues, drop with a counter.\n- Use resource attributes for `service.name`, `service.version`, `deployment.environment.name`, and the Kubernetes namespace and pod.\n\n## Linking quality signals\n\n- Eval and guardrail verdicts (prompt-injection check, PII redaction count, schema validation, groundedness score) are attributes or child spans on the same trace, so a bad answer can be traced back to the retrieval and the model attempt.\n- Offline eval runs set their own `service.name` and a run ID resource attribute so they never pollute production dashboards.\n\n## Tests\n\n- In-memory span exporter (OpenTelemetry SDK testing) with a stubbed provider (WireMock or MockWebServer):\n - one inbound request yields one trace with the expected span tree, including one span per retry and fallback attempt\n - required GenAI attributes present with values from the provider's usage and response\n - no message content, tool arguments, API keys, or Authorization headers in any attribute, event, or captured log line\n - content capture opt-in produces redacted content only when the flag is on\n - inbound `traceparent` is continued; outbound request carries it; context survives the streaming and async paths\n - metric labels contain none of the forbidden high-cardinality keys\n- A test that fails when an attribute name changes without the constants class and dashboards being updated.\n\n## Review checklist\n\n- [ ] One trace per inbound request; one client span per model attempt; tool and agent spans nested correctly\n- [ ] GenAI attribute and metric names from a pinned conventions version, defined in one place\n- [ ] Prompt, completion, tool argument, and retrieved text capture off by default and asserted in tests\n- [ ] Usage from the provider's usage block; estimates marked\n- [ ] No user, conversation, or response IDs as metric labels\n- [ ] W3C propagation across HTTP, async, streaming, and messaging\n- [ ] Tail sampling keeps errors, fallbacks, guardrail blocks, and slow requests\n- [ ] Export via OTLP to the Collector; exporter failures never fail requests\n\n## Copy-paste brief for instruction files\n\n```\nLLM tracing: one trace per inbound request, one CLIENT span per model attempt (retries and fallbacks visible), execute_tool and invoke_agent spans nested under it. Use OpenTelemetry GenAI attribute and metric names from the pinned conventions version, defined in one constants class; gateway facts go under llm.gateway.*. Never record prompts, completions, system instructions, tool arguments or results, retrieved text, keys, or auth headers by default; opt-in capture is flagged, time-boxed, and redacted. Usage comes from the provider's usage block. No user, conversation, or response IDs as metric labels. Propagate W3C trace context across HTTP, async, streaming, and queues. Export OTLP to the Collector with tail sampling that keeps errors, fallbacks, guardrail blocks, and slow requests. Tests assert the span tree, attributes, propagation, and the absence of content.\n```\n" + }, + { + "id": "llm-model-prompt-rollout-guardrails", + "title": "LLM Model and Prompt Rollout Guardrails", + "whenToUse": "Upgrading a model version, switching provider, or changing prompts, decoding parameters, or tool and output schemas on a production LLM route or gateway — one immutable release bundle per route with its ID in headers, traces, usage rows, and cache keys, dated model versions instead of floating aliases, a deliberate Azure OpenAI versionUpgradeOption in IaC, a model inventory with retirement dates and a scheduled check, prompts as versioned files loaded by ID, offline eval then side-effect-free shadow then sticky canary then GA with criteria committed before each stage, and a whole-bundle rollback by config that has been exercised.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "llm", + "release", + "canary", + "azure-openai", + "spring-boot", + "evaluation" + ], + "formatNotes": "All three. Copilot: path-scoped `.github/instructions/llm-rollout.instructions.md` with applyTo for `**/gateway/**`, `**/llm/**`, `**/prompts/**`, `**/rollouts/**`, and `**/infra/**/*.bicep`. Optional on-demand procedure at `.github/skills/llm-model-prompt-rollout-guardrails/SKILL.md`. Claude Code: `.claude/skills/llm-model-prompt-rollout-guardrails/SKILL.md` plus a CLAUDE.md fact that routes point at immutable bundle IDs and prompts are never edited at runtime. Codex: a short \"LLM rollouts\" brief in root `AGENTS.md` (bundle config path, prompt folder, model inventory file, rollout plan folder, rollback command); the procedure can live in `.agents/skills/llm-model-prompt-rollout-guardrails/SKILL.md`. Pair with llm-eval-ci-regression-gate for the offline stage, llm-gateway-routing-fallback-guardrails for target order, llm-cost-latency-budget-guardrails for the shadow budget, llm-tracing-observability-guardrails for the bundle attribute, llm-gateway-caching-guardrails for bundle-aware cache keys, and rag-ingestion-index-lifecycle-guardrails for embedding model changes. This skill owns the release bundle, version pinning and retirement tracking, the prompt registry, shadow and canary stages, rollout criteria, and rollback.", + "body": "# Skill: LLM Model and Prompt Rollout Guardrails\n\n## Goal\n\nA new model version, a provider switch, a prompt template edit, or a change to decoding parameters or tool schemas reaches production the way a risky code change does: as one pinned, versioned release, proven offline, watched on mirrored traffic, exposed to a small sticky cohort, and promoted or rolled back by criteria written down before the rollout started. Nothing changes model behavior in production without a diff, and the way back is a config flip that has already been exercised.\n\nTypical failures this skill prevents:\n\n1. **Unscheduled upgrades.** A deployment or router alias silently re-points to a newer model snapshot (provider auto-upgrade, `latest`-style alias), and output format, refusal rate, or tool-call behavior changes with no release on your side.\n2. **Retirement outages.** A pinned model version reaches its retirement date, the deployment starts returning errors, and nobody owned the date.\n3. **Version skew.** The model is rolled back but the prompt tuned for the new model stays, so production now runs a combination nobody ever tested.\n4. **Prompts edited in place.** A template changed in a database row or a portal, with no review, no version ID in telemetry, and no way to tell which answers came from which text.\n5. **Canaries that prove nothing.** Random per-request assignment that flips one user between styles mid-conversation, too little traffic to see the failing segment, and thresholds invented after the metric moved.\n6. **Shadow runs with side effects.** The candidate is mirrored real traffic and its tool calls send emails or write records.\n\nScoring a change against a golden set stays in **llm-eval-ci-regression-gate** and **rag-retrieval-eval-guardrails**. Target order and failover stay in **llm-gateway-routing-fallback-guardrails**. Token caps and price tables stay in **llm-cost-latency-budget-guardrails**. Span and metric names stay in **llm-tracing-observability-guardrails**. Re-embedding and index aliases stay in **rag-ingestion-index-lifecycle-guardrails**. This skill owns the release unit, model version pinning and retirement tracking, the prompt registry, shadow and canary stages, promotion and rollback criteria, and the tests for the switch.\n\n## When to apply\n\n- Upgrading a model version, moving to a new model family or variant, or switching provider for an existing route\n- Changing a system prompt, template, few-shot set, decoding parameters, or a tool or output schema used in production\n- A provider announces a retirement or a new default version for a deployment you use\n- Setting up Azure OpenAI (Foundry) deployments, or reviewing their upgrade policy\n- Reviewing a gateway where prompts live in code strings, a database, or a portal without versions\n\n## The release unit\n\nTreat these as one immutable bundle with an ID, e.g. `support-answer@2026-11-15.2`:\n\n- provider, deployment name, and exact model version or dated snapshot (never a floating alias)\n- prompt template IDs and content hashes (system, user, few-shot)\n- decoding parameters (temperature, max output tokens, reasoning effort, stop sequences)\n- tool definitions and output schema versions\n- retrieval settings the prompt depends on (index alias, top-k, re-ranker), by reference\n- guardrail and redaction policy versions\n\nRules:\n\n1. **One bundle per route, resolved at request time from config.** The gateway route points at a bundle ID; changing the bundle is a reviewed diff in Git (or a config store that records author and change), not a code redeploy and not a portal edit.\n2. **Bundles are immutable.** A fix is a new bundle ID. The previous bundle stays deployable until the new one has run at 100% for the agreed soak period.\n3. **Record the bundle ID everywhere.** Response header or metadata, trace attribute (`llm.gateway.bundle`), usage store row, eval run, and any cached entry key. Without it you cannot compare cohorts or invalidate caches.\n4. **Rollback restores the whole bundle**, never just the model or just the prompt.\n\n## Model version pinning and retirement\n\n1. **Pin dated versions.** On Azure OpenAI deployments set the model version explicitly and set `versionUpgradeOption` on purpose. `OnceNewDefaultVersionAvailable` moves you within about two weeks of a new default, which is an unscheduled release; `OnceCurrentVersionExpired` (also what an unset value means) upgrades only at retirement; `NoAutoUpgrade` keeps the version until retirement and then the deployment stops working. For production routes, prefer `NoAutoUpgrade` or `OnceCurrentVersionExpired` together with a tracked retirement date, and declare the choice in Bicep or the deployment script so it is reviewed. Provisioned (PTU) deployments are never auto-upgraded, so migration is always your job.\n2. **Other providers and routers:** request dated snapshot IDs rather than family aliases; record the `response.model` the provider returns and alert when it differs from the bundle's expected value. An unexpected model name is a rollout you did not schedule.\n3. **Model inventory as code.** A checked-in file listing each deployment, provider, model, version, upgrade policy, region, deployment type, retirement date, replacement candidate, owner, and the routes that use it.\n4. **Retirement is a dated task.** A scheduled CI job reads the inventory (and, where available, the provider's models or deprecation API) and fails or opens an issue when a retirement is within 90 days with no candidate bundle, and within 30 days with no completed canary. Subscribe owners to the provider's retirement notices (for Azure: Service Health alerts on Azure OpenAI Service).\n5. **Embedding models are not swapped in place.** A new embedding version means a re-index behind an alias (see rag-ingestion-index-lifecycle-guardrails), never a bundle edit.\n\n## Prompt registry\n\n- Prompts live as files in the repo (or a registry that is versioned and reviewed), one file per template with an ID, version, owner, intended model, variables, and output schema reference.\n- Load by ID and version; compute and log the content hash at startup. Fail startup if a referenced template or variable is missing.\n- No runtime edits in production. Emergency changes still go through a bundle and a fast-path review.\n- Templates are tested: render with fixture variables, check required sections and that untrusted input stays inside its delimiters (prompt-injection rules stay in llm-app-prompt-injection-guardrails).\n\n## Stages\n\nEvery change moves through stages, each with entry and exit criteria committed in a rollout plan file beside the bundle **before** the stage starts:\n\n1. **Offline eval.** The candidate bundle runs the golden set in CI against the current bundle (llm-eval-ci-regression-gate). Required for every change; a failed gate stops the rollout.\n2. **Shadow.** A sampled, stratified slice of live requests is sent to the candidate in the background. Users only see the current bundle's answer. Tool calls in the candidate are stubbed, dry-run, or sent to an isolated environment; never real side effects. Shadow output and comparisons follow the same redaction and retention rules as production content; store references and scores, not raw prompts, unless policy allows. Shadow runs on its own budget and quota so it can never throttle real traffic, and it is dropped first under load. Compare: schema validity, refusal and empty-answer rate, tool-call validity, output length, latency (TTFT and total), cost per request, and a paired judge score where calibrated. Use shadow for model and provider changes; small prompt-only edits may skip to canary if offline eval is strong.\n3. **Canary.** A small share of real traffic (start at 1 to 5 percent) on the candidate. Assignment is **sticky** by a stable hash of tenant or user (and conversation once started), so one conversation never switches bundles. Exclude or require approval for routes with irreversible actions. Ramp in steps (for example 5, 25, 50, 100), holding each step long enough to cover peak hours and the smallest segment you care about.\n4. **General availability.** The candidate becomes the route's bundle; the guard metrics stay as live alerts; the previous bundle stays deployable for the soak period, then its deployment can be removed.\n\n## Promotion and rollback criteria\n\n- Write them as data: metric, comparison against the control cohort (not last week), threshold, window, minimum sample size, and segments (tenant tier, language, route, tool).\n- Typical guard metrics: error and timeout rate, schema or parse failure rate, refusal and content-filter rate, tool-call error rate, p95 latency and TTFT, cost per successful request, fallback rate, user feedback or escalation rate, and eval sample scores on live traffic.\n- One guard breach halts the ramp and alerts the owner; a severe or repeated breach rolls back automatically to the previous bundle without waiting for a human.\n- Changing a threshold mid-rollout is a reviewed diff, never a dashboard edit.\n- A canary that has not reached the minimum sample in its window is \"hold\", not \"pass\".\n\n## Rollback\n\n- One command or config change sets the route back to the previous bundle ID; it takes effect without a redeploy and within a minute across replicas.\n- Exercise the rollback during the shadow or early canary stage, so it has been proven before anyone depends on it.\n- Caches keyed by bundle (or by model plus prompt version) do not serve the rolled-back bundle's answers to the restored bundle.\n- After rollback, keep the candidate's shadow and canary data for the postmortem.\n\n## Tests\n\n- Bundle resolution: a route resolves to exactly the pinned deployment, model version, prompt hash, parameters, and schema versions; an unknown bundle ID fails startup.\n- Sticky assignment: the same tenant or user hash lands in the same cohort across replicas and restarts; a conversation keeps its bundle when the percentage changes.\n- Shadow isolation: candidate tool calls never reach real executors; shadow failures and timeouts never affect the user response or its latency budget.\n- Drift alarm: a stubbed provider returning a different `model` value raises the mismatch metric.\n- Rollback: flipping the route config switches new requests to the previous bundle without restart.\n- Inventory check: the retirement job fails on a fixture deployment retiring in 20 days without a completed canary.\n\n## Review checklist\n\n- [ ] Each production route points at an immutable bundle ID covering model version, prompt hashes, parameters, tool and output schemas\n- [ ] No floating model aliases; Azure `versionUpgradeOption` set deliberately and declared in IaC\n- [ ] Model inventory with retirement dates, owners, and a scheduled check\n- [ ] Prompts versioned in the repo, loaded by ID, hash logged; no runtime edits\n- [ ] Bundle ID in headers, traces, usage rows, eval runs, and cache keys\n- [ ] Offline eval, shadow (no side effects, own budget), sticky canary, then GA\n- [ ] Promotion and rollback criteria committed before each stage; automatic rollback on severe breach\n- [ ] Rollback flips the whole bundle by config and has been exercised\n\n## Copy-paste brief for instruction files\n\n```\nLLM rollouts: every production route points at an immutable bundle (provider deployment + dated model version, prompt IDs and hashes, decoding params, tool and output schema versions). No floating model aliases; set Azure OpenAI versionUpgradeOption deliberately in IaC and keep a model inventory with retirement dates and a scheduled check. Prompts are versioned files loaded by ID; no runtime edits. Record the bundle ID in headers, traces, usage rows, eval runs, and cache keys. A change goes offline eval -> shadow (stubbed tools, own budget, no user impact) -> sticky canary (hash of tenant or user, ramp in steps) -> GA, with promotion and rollback criteria committed before each stage. Rollback flips the whole bundle by config, without redeploy, and is exercised before the canary.\n```\n" } ] } From 00d70a02ddad07c86a5683e33e72b0c085ffe55d Mon Sep 17 00:00:00 2001 From: Ramkumar Ethiraj <64294490+rmkr-dev@users.noreply.github.com> Date: Sun, 15 Nov 2026 05:13:40 +0000 Subject: [PATCH 2/2] Add prompt for rolling out LLM model and prompt changes --- promptbook/prompts.json | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/promptbook/prompts.json b/promptbook/prompts.json index 497dc9f..6a33758 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -1162,6 +1162,26 @@ ], "formatNotes": "All three. Point the tool at the provider clients, routing and retry code, streaming handler, Observation or tracer config, logback config, Collector config, and the test folder. Copilot: llm-tracing path instructions plus those files in agent mode (or save the prompt as `.github/prompts/add-llm-tracing-and-genai-metrics.prompt.md`). Claude Code: the llm-tracing-observability-guardrails skill plus those files. Codex: the AGENTS.md LLM tracing section, then the diff. Leave budgets, Collector cluster setup, redaction rules, streaming deadlines, and eval scoring to their own skills.", "body": "Task: Add or fix OpenTelemetry tracing and metrics for the LLM service or gateway I specify so that one inbound request produces one readable trace with model attempts, retrieval, tools, and guardrail checks, using the GenAI semantic conventions, with no prompt or completion text in telemetry by default. Finish with a minimal diff, config, and tests.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Service: {{APP_NAME}} at {{APP_PATH}}\n- Stack: {{STACK}} (Spring Boot version; Spring AI | LangChain4j | hand-rolled HTTP clients; WebFlux or MVC; virtual threads?)\n- Instrumentation today: {{INSTRUMENTATION}} (OpenTelemetry Java agent | Micrometer Tracing with OTel bridge | vendor SDK | none)\n- Providers and routes: {{PROVIDERS}} (Azure OpenAI, OpenAI-compatible routers, Bedrock, others; retry and fallback logic location)\n- Backend: {{BACKEND}} (OTel Collector then Datadog | Azure Monitor | Tempo/Grafana | other)\n- Conventions version: {{SEMCONV_VERSION}} (pin one; note the instrumentation library's GenAI stability setting if it has one)\n- Data rules: {{DATA_RULES}} (what may never leave the service; telemetry retention; redaction hook to reuse)\n- Async paths: {{ASYNC}} (streaming/SSE, reactive, @Async, queues)\n\nRequirements:\n\n1. Inventory\n - Table: operation (inbound endpoint, chat, embeddings, retrieval, tool, agent loop, guardrail) | span today? | parent correct? | attributes today | content captured? | metrics today | labels | propagation across async?\n - Flag new traces per upstream call, missing retry/fallback attempts, prompts or completions in spans or logs, user/conversation IDs as metric labels, estimated usage where the provider returned real usage, and vendor-specific names where GenAI names exist\n\n2. Span tree\n - SERVER span for the inbound request; CLIENT span per model attempt named `{operation} {model}`; retrieval span; `execute_tool {tool}` INTERNAL spans; `invoke_agent {agent}` around agent loops; INTERNAL spans or events for guardrail checks\n - Attempt number and routing or fallback reason on each attempt span; span status ERROR with `error.type` only for real failures; refusals recorded as finish reasons\n\n3. Attributes\n - GenAI attributes from {{SEMCONV_VERSION}}: operation name, provider name, request and response model, request parameters actually sent, response ID, finish reasons, input and output token usage from the provider usage block, tool name and call ID, agent name, conversation ID (span only), server address and port\n - All GenAI names in one constants class; gateway-specific facts (route, tenant, deployment, cache hit, budget decision, fallback reason) under `llm.gateway.*`\n - Mark estimated usage explicitly when a stream ends without a usage block\n\n4. Content capture\n - Off by default for input and output messages, system instructions, tool definitions, tool arguments and results, and retrieved text, in spans, events, and logs\n - Disable framework prompt and completion logging and HTTP wire logging; record shape instead (message count, token counts, chunk IDs and scores)\n - Optional opt-in: named flag per environment or tenant, time-boxed, passed through the existing redaction hook, preferably exported to a separate store referenced by ID\n\n5. Metrics\n - GenAI token usage histogram with token type, and the duration histograms the pinned version defines (per-operation in newer versions); time to first token and time per output token for streaming\n - Labels limited to operation, provider, request and response model, route, outcome or `error.type`, token type; bounded tenant only if small\n - If using Micrometer Observation, map exported names to the conventions with an observation convention class\n\n6. Propagation\n - W3C trace context continued from the caller and sent to providers; preserved across {{ASYNC}}; injected into message headers for queues\n - Baggage restricted to non-sensitive low-cardinality keys; untrusted inbound baggage stripped before provider calls\n - `trace_id` and `span_id` in log MDC\n\n7. Sampling and export\n - SDK head sampling plus Collector tail sampling keeping errors, fallbacks, guardrail blocks, and requests above the latency SLO\n - OTLP to the Collector; Collector attribute-delete processor for content keys as a backstop; resource attributes for service name, version, environment, namespace, and pod\n - Exporter failure never fails a request; bounded queue with a dropped-spans counter\n\n8. Tests\n - In-memory span exporter with a stubbed provider: span tree per request including retry and fallback attempts; required attributes; no content, keys, or Authorization headers anywhere; opt-in path emits redacted content only when enabled; inbound traceparent continued and outbound carries it; context survives streaming and async paths; forbidden metric labels absent\n - A test that pins the attribute names in the constants class\n\n9. Verification\n - One example trace (attribute keys only, no content) before and after, the updated inventory table, and the dashboard or monitor queries that need renaming\n\nConstraints:\n- Minimal diff. Reuse the existing tracer, Observation registry, and Collector; no new vendor SDK.\n- Do not loosen redaction or delete tests to make CI pass. Do not put real prompts or customer data in fixtures.\n- Leave budgets and price tables, Collector cluster setup, log formatting, redaction rules, streaming deadlines, and eval scoring 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. Span tree and attribute diff (constants class included)\n3. Content capture settings and redaction hook wiring\n4. Metrics, propagation, sampling, and Collector config diff\n5. Tests added and what each asserts\n\nStart from {{APP_PATH}}. Remove content leaks first, then fix trace continuity and per-attempt spans, then names, metrics, and sampling.\n" + }, + { + "id": "roll-out-llm-model-or-prompt-change", + "title": "Roll Out an LLM Model or Prompt Change Safely", + "whenToUse": "Ship a model version upgrade, provider switch, forced retirement migration, or prompt and parameter change on an LLM route — inventory of versions and retirement dates, immutable release bundle per route, explicit Azure OpenAI versionUpgradeOption in IaC, model mismatch alarm, prompt registry, rollout plan with pre-committed criteria, side-effect-free shadow, sticky canary ramp, automatic rollback, and a rollback drill with tests.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "llm", + "release", + "canary", + "azure-openai", + "spring-boot", + "evaluation" + ], + "formatNotes": "All three. Point the tool at the gateway route config, provider clients, prompt templates, Azure OpenAI Bicep or Terraform, the eval job, and the test folder. Copilot: llm-rollout path instructions plus those files in agent mode (or save the prompt as `.github/prompts/roll-out-llm-model-or-prompt-change.prompt.md`). Claude Code: the llm-model-prompt-rollout-guardrails skill plus those files. Codex: the AGENTS.md LLM rollouts section, then the diff. Leave golden-set scoring, routing order, budgets, tracing names, and re-indexing to their own skills.", + "body": "Task: Put the LLM route or gateway I specify on versioned, staged releases so that a model version upgrade, provider switch, or prompt and parameter change ships as one pinned bundle through offline eval, shadow, and a sticky canary, with criteria committed up front and a tested one-step rollback. Finish with a minimal diff, config, and tests.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Service: {{APP_NAME}} at {{APP_PATH}}\n- Stack: {{STACK}} (Spring Boot version; Spring AI | LangChain4j | hand-rolled HTTP clients; config source: application.yaml | App Configuration | database)\n- Routes and providers: {{ROUTES}} (route names, Azure OpenAI deployments, Bedrock, OpenAI-compatible routers; where prompts live today)\n- Change to ship: {{CHANGE}} (new model version or family, provider switch, prompt edit, parameter or schema change, forced retirement)\n- Deployment config: {{IAC}} (Bicep or Terraform files declaring Azure OpenAI deployments; versionUpgradeOption today)\n- Eval gate: {{EVAL}} (existing golden-set job and command, judge setup)\n- Guard metrics source: {{METRICS}} (usage store, OpenTelemetry backend, feedback signal)\n- Risky routes: {{SIDE_EFFECTS}} (routes or tools with irreversible actions)\n\nRequirements:\n\n1. Inventory\n - Table: route | provider deployment | model and version requested | model returned | upgrade policy | retirement date | prompt location and versioning | parameters source | bundle ID today? | rollback path today\n - Flag floating aliases, unset or auto-upgrading versions on production routes, prompts edited at runtime, missing version IDs in telemetry, and any retirement within 90 days\n\n2. Release bundle\n - Define an immutable bundle per route: deployment, dated model version, prompt template IDs and hashes, decoding parameters, tool and output schema versions, retrieval settings by reference, guardrail policy versions\n - Route config points at a bundle ID; resolution happens at request time; unknown IDs fail startup\n - Bundle ID in response metadata, `llm.gateway.bundle` span attribute, usage rows, eval runs, and cache keys\n\n3. Model pinning and retirement\n - Set `versionUpgradeOption` explicitly in {{IAC}} for every Azure OpenAI deployment and explain the choice; note PTU deployments never auto-upgrade\n - Use dated snapshot IDs for other providers; emit a mismatch metric when the returned model differs from the bundle\n - Add a checked-in model inventory and a scheduled job that opens an issue or fails at 90 days to retirement without a candidate bundle and at 30 days without a completed canary\n\n4. Prompt registry\n - Move templates to versioned files (ID, version, owner, intended model, variables, schema reference); load by ID; log the content hash; no runtime edits\n - Render tests with fixture variables, checking required sections and that untrusted input stays delimited\n\n5. Stages and criteria\n - Rollout plan file per change: stages (offline eval, shadow, canary steps, GA), and per stage the metric, comparison to the control cohort, threshold, window, minimum sample, segments, and action (hold, halt, roll back)\n - Offline: wire the candidate bundle into {{EVAL}}\n - Shadow: sampled and stratified mirror, user sees only the current answer, candidate tools stubbed or isolated, separate budget and quota, dropped first under load, content handled under the same redaction and retention rules\n - Canary: sticky assignment by stable hash of tenant or user, conversation pinned to its bundle, {{SIDE_EFFECTS}} excluded or approval-gated, stepwise ramp\n - Automatic rollback on severe or repeated breach; insufficient sample means hold\n\n6. Rollback\n - One config change returns the route to the previous bundle without redeploy; propagate to all replicas within a minute\n - Run it once during shadow or early canary and record the result\n\n7. Tests\n - Bundle resolution and startup failure on unknown IDs; sticky cohorts stable across replicas and restarts and when the percentage changes; shadow never executes real tools and never affects user latency or errors; model mismatch metric fires on a stubbed different `model`; rollback switches new requests without restart; retirement job fails on a fixture deployment near retirement\n\n8. Verification\n - Updated inventory table, the bundle and rollout plan for {{CHANGE}}, a sample shadow comparison report (scores and IDs only, no content), and the rollback drill result\n\nConstraints:\n- Minimal diff. Reuse the existing gateway routing, config source, eval job, and telemetry; no new platform.\n- Never run candidate side effects in shadow. Never loosen eval thresholds or delete tests to pass a stage.\n- Leave golden-set scoring, routing and fallback order, budgets and prices, tracing names, and re-indexing to their existing skills; call their hooks.\n- Copilot, Claude Code, and Codex: concrete diffs, the inventory table, the rollout plan file, and a checklist. Do not paste this prompt into AGENTS.md.\n\nOutput format:\n1. Inventory table with the gaps found\n2. Bundle definition, route config, and IaC diff (upgrade policy included)\n3. Prompt registry layout and loader diff\n4. Rollout plan file, shadow and canary wiring, and rollback switch\n5. Tests added and what each asserts\n\nStart from {{APP_PATH}}. Pin versions and stop unscheduled upgrades first, then introduce bundles and the registry, then shadow, canary, and the rollback drill.\n" } ] }