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 @@ -1142,6 +1142,26 @@
],
"formatNotes": "All three. Point the tool at the connectors, chunker, embedding client, index client and schema, the retrieval query builder, scheduler config, and the test folder. Copilot: rag-ingestion path instructions plus those files in agent mode (or save the prompt as `.github/prompts/harden-rag-ingestion-pipeline.prompt.md`). Claude Code: the rag-ingestion-index-lifecycle-guardrails skill plus the connector and index files. Codex: the AGENTS.md RAG ingestion section, then the diff. Leave retrieval quality metrics, query-time injection defences, redaction rules, cache internals, and pricing to their own skills.",
"body": "Task: Make the RAG ingestion pipeline and search index I specify a faithful, permission-correct copy of its sources. Updated documents must leave no stale chunks, deleted or erased documents must disappear from retrieval and every cache, permission changes must reach the index quickly, and an embedding model or chunking change must ship as a reversible blue/green re-index. Finish with a minimal diff, config, and tests.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Pipeline and module: {{APP_NAME}} at {{APP_PATH}}\n- Stack: {{STACK}} (Spring Boot version; Spring AI | LangChain4j | Spring Batch | Spark/Databricks job | custom workers)\n- Sources: {{SOURCES}} (SharePoint, Confluence, Git, blob storage, database, ticketing) and each one's change feed, delete detection, and ACL model\n- Index store: {{STORE}} (Azure AI Search | pgvector | OpenSearch/Elasticsearch | Qdrant | other) and whether it supports aliases and filtered vector search\n- Embedding model: {{EMBEDDING_MODEL}} (name, version, dimensions) and any planned change\n- Identity: {{IDENTITY}} (Entra ID or other; where user and group object IDs come from at ingestion and at query time)\n- Data rules: {{DATA_RULES}} (classification, retention, residency, erasure requirements)\n- Answer caches: {{CACHES}} (exact or semantic caches that store answers citing this index, or \"none\")\n- Observability: {{OBSERVABILITY}} (Micrometer | OpenTelemetry | both) and the cost ledger for embedding spend\n- Retrieval eval: {{EVAL}} (existing golden set and CI job, or \"none\")\n\nRequirements:\n\n1. Inventory\n - Table: source | change feed or polling | delete detection | ACL source and format | index or alias name | embedding model and dims | chunker version | upsert-only? | cursor saved after success? | freshness today\n - Flag upsert-only writes, missing delete paths, ACLs not stored on chunks, hard-coded index names, mixed embedding versions, and cursors saved before writes\n\n2. Identity and manifest\n - Stable document ID from the source system; deterministic chunk IDs (doc ID + sequence or position hash)\n - Chunk fields: doc ID, source, source URI, content version, ACL version, chunker version, embedding model and version, dims, ingested and source-modified times, classification, principal IDs\n - A manifest table per document: current content and ACL versions, emitted chunk IDs, last success, last error\n\n3. Sync loop\n - Change feed or modified-since polling per source; cursor stored with the batch outcome and advanced only after index writes succeed\n - Classify changes: content (re-chunk, re-embed changed chunks), ACL only (metadata update), delete (tombstone). ACL and delete events take a fast path\n - Hash-skip unchanged documents and chunks; cache embeddings by chunk hash and model version\n - Replace chunk sets: write the new set, then delete that document's chunks not in it\n - Idempotent, order-safe workers: an older version never overwrites a newer one, and nothing recreates a tombstoned document\n - Batch calls, back off on 429/503, check per-item status on bulk responses, dead-letter by doc ID without content\n\n4. Deletes and erasure\n - Tombstone first; retrieval excludes tombstoned IDs at once; physical cleanup follows\n - Cleanup reaches chunks, vectors, keyword entries, staging and extracted text, embedding cache, answer caches in {{CACHES}}, eval fixtures, and backups per {{DATA_RULES}}\n - Configure the connector's own delete detection where it needs it (soft-delete flag or deletion policy)\n - Scheduled reconciliation: source IDs vs manifest vs index; remove orphans, re-queue version mismatches\n\n5. Permissions\n - Principal IDs (user, group, tenant) on every chunk as filterable fields\n - One query-filter builder that takes the caller's authenticated identity and applies the filter inside the vector or hybrid query, never after top-k\n - ACL changes update all chunks of the document and invalidate caches keyed by the old scope\n - Missing or unreadable ACL means not retrievable (fail closed). Document the group-resolution cache window and nested-group handling\n - Tenant filter mandatory on every query; separate index per tenant where {{DATA_RULES}} require it\n\n6. Embedding versioning and blue/green re-index\n - One embedding model version and dimension per index, recorded on the index or in a registry; the query embedder reads it from there and fails startup on mismatch\n - Applications read and write through an alias (or a config-switched table for pgvector); no index names in app code\n - Script: create new index, backfill from source or manifest text, dual-write changes, deletes, and ACL updates during backfill, verify counts per source, zero chunks without ACLs, tombstones absent, and {{EVAL}} passing, switch the alias in one call (respect documented propagation delay), keep the old index read-only for a rollback window, then retire it\n - pgvector: `CREATE INDEX CONCURRENTLY` and a validity check before switching\n - Answer caches partitioned by index or embedding version, or purged on switch\n\n7. Ingestion-time safety\n - Redact secrets and sensitive personal data before chunking and embedding (reuse the existing redaction hook)\n - Provenance and source trust level on each chunk; allow-listed sources only; instruction-like content flagged for review\n - Connectors use managed or workload identity with read-only scopes\n\n8. Freshness and metrics ({{OBSERVABILITY}})\n - SLOs per source for content, ACL, and delete visibility\n - `rag_ingest_documents_total` (`source`, `action`), `rag_ingest_lag_seconds` (`source`, `change_type`), `rag_index_chunks` (`index`, `source`), `rag_reconcile_drift_total` (`source`, `kind`), `rag_embedding_tokens_total` (`source`, `embedding_model`), `rag_ingest_cursor_age_seconds` (`source`)\n - Alerts on cursor age, ACL and delete lag over SLO, any `missing_acl` drift. No document text, titles, or user names in labels; logs carry IDs and versions\n\n9. Tests (synthetic corpus; Testcontainers for the store where possible)\n - Re-ingest is idempotent; shrinking a document leaves exactly the new chunk count\n - Delete hides immediately and cleans up later; a late update does not resurrect it; out-of-order versions resolve correctly\n - Revoked principal sees nothing, granted principal sees the document, chunk without ACL never returns\n - Failed write leaves the cursor unchanged\n - Query-model vs index-model mismatch fails startup or health check\n - Blue/green run on a fixture corpus switches, passes checks, and rolls back\n - Erasure leaves zero chunks, vectors, cache entries, and staging files\n\n10. Verification\n - Updated inventory table, drift found by the first reconciliation run, freshness per source before and after, and the re-index runbook\n\nConstraints:\n- Minimal diff. Reuse the existing store client, scheduler, messaging, and metrics registry; no new ingestion framework.\n- Do not weaken an ACL filter, skip a tombstone, or delete a test to make CI pass.\n- Never copy real customer documents into fixtures.\n- Leave retrieval quality metrics, query-time prompt-injection defences, redaction rules, cache internals, and pricing 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. Identity, manifest, and sync loop diff\n3. Delete, erasure, reconciliation, and ACL diff\n4. Alias, embedding version check, and blue/green re-index script\n5. Metrics, alerts, and the tests added with what each asserts\n\nStart from {{APP_PATH}}. Fix deletes, ACLs, and orphan chunks first, then the cursor and reconciliation, then the alias and re-index path.\n"
},
{
"id": "add-llm-tracing-and-genai-metrics",
"title": "Add LLM Tracing and GenAI Metrics Without Leaking Prompts",
"whenToUse": "Wire or fix OpenTelemetry for an LLM service or gateway — inventory of spans and leaks, per-attempt CLIENT spans for retries and fallbacks, tool and agent spans, GenAI attributes and metrics from a pinned conventions version, content capture off by default with redacted opt-in, provider usage instead of estimates, bounded metric labels, W3C propagation across streaming and async, Collector tail sampling and attribute backstop, and in-memory exporter tests.",
"tools": [
"copilot",
"claude-code",
"codex"
],
"tags": [
"llm",
"observability",
"opentelemetry",
"tracing",
"spring-boot",
"privacy"
],
"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"
}
]
}
Loading
Loading