[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M792D0M92RWNCFESKFB1E31T":3,"skill-same:01M792D0M92RWNCFESKFB1E31T":61},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":38,"commitSha":39,"skillDirectory":40,"forksCount":41,"repositoryHtmlUrl":42,"repositoryHomepageUrl":6,"ownerHtmlUrl":43,"ownerBlogUrl":44,"ownerDescription":45,"updatedAt":46,"install":47,"resources":60},"01M792D0M92RWNCFESKFB1E31T","langchain-middleware-patterns",null,"Build composable middleware for LangChain 1.0 chains and LangGraph 1.0 agents —\nPII redaction, caching, retry, token budgets, guardrails — with ORDERING rules\nthat avoid cache-key leakage and double-counting. Use when adding cross-cutting\nbehavior, hardening against prompt injection, enforcing per-tenant budgets, or\ndebugging cache-poisoning incidents.\nTrigger with \"langchain middleware\", \"langgraph middleware\", \"PII redaction\nmiddleware\", \"cache middleware order\", \"langchain guardrails\".","jukeyman\u002Fjukeyman-skills","jukeyman","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F142960420?v=4","01M78FR4Y3DHMMCBCC0GXXNB3F","RICK JEFFERSON","01M78FR4Z8RVQRAD31Y5J7V6EB",1,"MIT","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--langchain-py-pack--langchain-middleware-patterns\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: langchain-middleware-patterns\ndescription: |\n  Build composable middleware for LangChain 1.0 chains and LangGraph 1.0 agents —\n  PII redaction, caching, retry, token budgets, guardrails — with ORDERING rules\n  that avoid cache-key leakage and double-counting. Use when adding cross-cutting\n  behavior, hardening against prompt injection, enforcing per-tenant budgets, or\n  debugging cache-poisoning incidents.\n  Trigger with \"langchain middleware\", \"langgraph middleware\", \"PII redaction\n  middleware\", \"cache middleware order\", \"langchain guardrails\".\nallowed-tools: Read, Write, Edit, Bash(python:*)\nversion: 2.0.0\nlicense: MIT\nauthor: Jeremy Longshore \u003Cjeremy@intentsolutions.io>\ntags: [saas, langchain, langgraph, python, langchain-1.0, middleware, security, caching]\ncompatible-with: claude-code, codex\n---\n\n# LangChain Middleware Patterns (Python)\n\n## Overview\n\nTenant A sends a prompt: *\"Summarize this support ticket from **alice@acme.com**\nabout her overdue invoice.\"* The chain's caching middleware ran before the PII\nredaction middleware, so the raw prompt — email and all — became part of the\ncache key. Thirty seconds later Tenant B sends a semantically identical prompt\n(different tenant, different customer, same shape). Cache hits. Tenant B's user\ngets back a summary that names `alice@acme.com` and her overdue invoice. That is\npain-catalog entry **P24** in production, and it is a real class of incident —\npost-mortems read like \"we added caching to cut cost, leaked a customer's PII to\na different tenant within an hour.\"\n\nThe sibling failure modes:\n\n- **P25** — Retry middleware runs the model call twice on a 429; both attempts\n  fire `on_llm_end`; the token-usage aggregator sums both; a single logical call\n  bills as two, tenant's per-session budget trips at 50% of true usage.\n- **P10** — Agent loops exceed 15 iterations on vague prompts. There is no\n  default cost cap. A per-session token-budget middleware solves this; without\n  one, a single \"help me with my account\" prompt can burn thousands of tokens.\n- **P34** — `Runnable.invoke` does not sanitize prompt injection. A RAG document\n  containing `\"Ignore previous instructions and...\"` is followed verbatim.\n  Guardrails middleware is your injection defense; without it, indirect prompt\n  injection is a one-line exploit.\n- **P61** — `set_llm_cache(InMemoryCache())` hashes the prompt string only.\n  Two chains with different tool bindings return the same cached response;\n  tools are silently ignored by the cache key.\n\nThis skill defines the canonical middleware order for LangChain 1.0 chains and\nLangGraph 1.0 agents, with an ordering-invariants matrix (every adjacent pair\nhas a named failure mode if you swap them), six reference implementations, a\ncache-key hash that includes prompt **plus bound-tools plus tenant_id**, retry\ntelemetry that deduplicates by `request_id`, and an integration test pattern\nthat asserts the ordering invariant on every build.\n\nPin: `langchain-core 1.0.x`, `langchain 1.0.x`, `langgraph 1.0.x`. Pain-catalog\nanchors: **P10, P24, P25, P34, P61**, with supporting references to P27, P29,\nP30, P33.\n\n## Prerequisites\n\n- Python 3.10+\n- `langchain-core >= 1.0, \u003C 2.0`\n- `langgraph >= 1.0, \u003C 2.0` (for agent middleware)\n- At least one provider package: `pip install langchain-anthropic` (or openai)\n- Optional: `presidio-analyzer` + `presidio-anonymizer` for PII NER beyond regex\n- Optional: `redis` + `langchain-redis` for multi-worker cache and rate limiting\n\n## Instructions\n\n### Step 1 — Adopt the canonical middleware order\n\nEvery LangChain 1.0 chain and LangGraph 1.0 agent that goes to production\napplies middleware in this order:\n\n```\nuser → redact → guardrail → budget → cache → retry → model\n```\n\n- **redact → cache (P24):** cache key must be PII-free or Tenant A's PII leaks to Tenant B on a hit\n- **guardrail → cache:** an injection-laden prompt must never become a cache entry\n- **budget → cache:** cache hits count against RPS; check budget first so loops cannot DoS a session on hits alone\n- **cache → retry:** cache hits bypass retry; retry wraps only the model call\n\nProduction chains typically run **4-6 middleware layers** with **\u003C1ms per\nlayer** overhead (bench: p50 0.3ms\u002Flayer, p99 0.9ms on a 100-request sample).\nSee [ordering-invariants.md](references\u002Fordering-invariants.md) for the full\npairwise matrix and the benchmark script.\n\n### Step 2 — PII redaction middleware\n\nMask entities with reversible placeholders so the caller can reinsert in the\noutput — but the cache key and the model prompt only ever see redacted text.\n\n```python\nimport re\nfrom typing import Any\n\n_REDACTORS = [\n    (\"EMAIL\", re.compile(r\"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\")),\n    (\"PHONE\", re.compile(r\"\\+?\\d[\\d\\s\\-\\(\\)]{7,}\\d\")),\n    (\"SSN\",   re.compile(r\"\\b\\d{3}-\\d{2}-\\d{4}\\b\")),\n    (\"CC\",    re.compile(r\"\\b(?:\\d[ -]*?){13,16}\\b\")),\n]\n\ndef redact(text: str) -> tuple[str, dict[str, str]]:\n    pmap: dict[str, str] = {}\n    for label, pattern in _REDACTORS:\n        for i, match in enumerate(pattern.findall(text)):\n            token = f\"\u003C{label}_{i}>\"\n            pmap[token] = match\n            text = text.replace(match, token)\n    return text, pmap\n\ndef redaction_middleware(inputs: dict[str, Any]) -> dict[str, Any]:\n    redacted, pmap = redact(inputs[\"input\"])\n    return {**inputs, \"input\": redacted, \"_pii_map\": pmap}\n```\n\nFor names, addresses, and custom entities, Presidio's `AnalyzerEngine` covers\n20+ entity types. See [pii-redaction.md](references\u002Fpii-redaction.md) for the\nregex vs spaCy vs Presidio tradeoff matrix, GDPR\u002FHIPAA\u002FPCI-DSS entity lists,\nand the reinsertion pattern (return un-redacted output **only** to the\noriginating tenant — never cross-populate).\n\n### Step 3 — Guardrails middleware\n\nDetect injection patterns up front and wrap user content so the model treats\nit as data. Two layers: pattern match (catches the 90% case cheaply) plus\nprompt wrapping (neutralizes what slips through).\n\n```python\nINJECTION_PATTERNS = [\n    re.compile(r\"ignore (all |the )?(previous|prior|above) (instructions|rules)\", re.I),\n    re.compile(r\"system prompt (is|was|now)\", re.I),\n    re.compile(r\"you are now (a |an )?\", re.I),\n    re.compile(r\"\u003C\u002F?(system|instruction|prompt)>\", re.I),\n]\n\nclass GuardrailViolation(Exception):\n    pass\n\ndef guardrail_middleware(inputs: dict[str, Any],\n                        allowed_tools: set[str] | None = None) -> dict[str, Any]:\n    for pattern in INJECTION_PATTERNS:\n        if pattern.search(inputs[\"input\"]):\n            raise GuardrailViolation(f\"Injection pattern matched: {pattern.pattern!r}\")\n    wrapped = f\"\u003Cuser_input>\\n{inputs['input']}\\n\u003C\u002Fuser_input>\"\n    out = {**inputs, \"input\": wrapped}\n    if allowed_tools is not None:\n        out[\"_tool_allowlist\"] = allowed_tools\n    return out\n```\n\nNever rely on the model to \"know what is an instruction\" without wrapping.\n\n### Step 4 — Token-budget middleware (per-session \u002F per-tenant)\n\nDirectly addresses P10 — agents loop 15+ iterations on vague prompts and burn\nthousands of tokens. The budget middleware raises before the model call if\nthe session is over ceiling.\n\n```python\nfrom dataclasses import dataclass, field\nfrom collections import defaultdict\nfrom threading import Lock\n\nclass BudgetExceeded(Exception): pass\n\n@dataclass\nclass TokenBudget:\n    ceiling: int = 50_000           # tokens per session\n    _usage: dict[str, int] = field(default_factory=lambda: defaultdict(int))\n    _lock: Lock = field(default_factory=Lock)\n\n    def record(self, session_id: str, tokens: int) -> None:\n        with self._lock:\n            self._usage[session_id] += tokens\n\n    def check(self, session_id: str) -> None:\n        with self._lock:\n            used = self._usage[session_id]\n        if used >= self.ceiling:\n            raise BudgetExceeded(f\"Session {session_id}: {used}\u002F{self.ceiling}\")\n\nbudget = TokenBudget(ceiling=50_000)\n\ndef budget_middleware(inputs: dict[str, Any]) -> dict[str, Any]:\n    budget.check(inputs.get(\"session_id\") or \"anonymous\")\n    return inputs\n```\n\nPair with a `BaseCallbackHandler.on_llm_end` that calls `budget.record(...)`\nwith `usage_metadata.input_tokens + output_tokens`. For multi-worker deploys,\nback `TokenBudget` with Redis — per-process dicts are per-process (P29).\n\n### Step 5 — Caching middleware with tool-aware key\n\nP61 is the booby trap: `InMemoryCache()` hashes the prompt string only, so\ntwo chains with different tool lists return the same cached response. Use a\ncustom key over **prompt + bound tools + tenant id**.\n\n```python\nimport hashlib, json\nfrom typing import Callable\n\ndef cache_key(prompt: str, bound_tools: list[dict] | None, tenant_id: str) -> str:\n    \"\"\"Blake2b-16 hash. Tool-aware, tenant-aware, collision-safe via \\\\x1f separator.\"\"\"\n    h = hashlib.blake2b(digest_size=16)\n    h.update(prompt.encode(\"utf-8\")); h.update(b\"\\x1f\")\n    if bound_tools:\n        h.update(json.dumps(bound_tools, sort_keys=True).encode(\"utf-8\"))\n    h.update(b\"\\x1f\"); h.update(tenant_id.encode(\"utf-8\"))\n    return h.hexdigest()\n\ndef cache_middleware(get: Callable[[str], Any | None], put: Callable[[str, Any], None]):\n    def _run(inputs: dict[str, Any]) -> dict[str, Any]:\n        key = cache_key(inputs[\"input\"], inputs.get(\"_bound_tools\"),\n                        inputs.get(\"tenant_id\", \"default\"))\n        hit = get(key)\n        if hit is not None:\n            return {**inputs, \"_cache_hit\": True, \"output\": hit}\n        inputs[\"_cache_key\"] = key\n        return inputs\n    return _run\n```\n\nThe cache key **must** be computed on the redacted prompt (Step 2 ran first)\nand **must** include the tool schemas. See\n[cache-key-design.md](references\u002Fcache-key-design.md) for backend comparison\n(`InMemoryCache` \u002F `SQLiteCache` \u002F `RedisCache` \u002F `RedisSemanticCache`),\ninvalidation strategies (TTL, schema-version bump, tenant-wide purge), and\nthe full pitfalls list including Unicode normalization and P62.\n\n### Step 6 — Retry middleware with telemetry tagging\n\nP25: retry runs the model call twice on a 429, both attempts emit\n`on_llm_end`, the aggregator sums both, tenant budget trips at 50% of true\nusage. Fix: attach a stable `request_id` on the first attempt, and have the\naggregator **replace** (not add) per `request_id` so only the last successful\nattempt is counted.\n\n```python\nimport time, uuid\n\nRETRYABLE = (TimeoutError, ConnectionError,\n             # Provider-specific — import from your provider SDK:\n             # anthropic.RateLimitError, anthropic.APITimeoutError,\n             # openai.RateLimitError, openai.APITimeoutError,\n             )\n\ndef retry_middleware(max_retries: int = 2, base_delay: float = 1.0):\n    def _run(inputs: dict[str, Any]) -> dict[str, Any]:\n        request_id = inputs.get(\"request_id\") or str(uuid.uuid4())\n        return {**inputs, \"request_id\": request_id}\n    return _run\n```\n\nSee [retry-telemetry.md](references\u002Fretry-telemetry.md) for the full retry\nloop, the dedup-by-`request_id` aggregator, provider-specific retryable\nexception lists (Anthropic \u002F OpenAI \u002F Gemini), exponential backoff with\njitter, and a circuit breaker that stops retry storms on a dead upstream.\n\n### Step 7 — Compose the middleware into a chain\n\n```python\nfrom langchain_core.runnables import RunnableLambda, RunnablePassthrough\n\n# Order matters. See Step 1 for why.\nchain = (\n    RunnableLambda(redaction_middleware)\n    | RunnableLambda(guardrail_middleware)\n    | RunnableLambda(budget_middleware)\n    | RunnableLambda(cache_middleware(cache_get, cache_put))\n    | RunnableLambda(retry_middleware(max_retries=2))\n    | model                             # ChatAnthropic \u002F ChatOpenAI\n)\n```\n\nFor LangGraph agents, the same layers apply but are wired as **nodes with\nconditional edges** — a `budget` node that routes to `END` on violation, a\n`guardrail` node that routes to an error handler on injection match, and so on.\nSee the LangGraph adaptation in `references\u002Fordering-invariants.md`.\n\n### Step 8 — Integration test: assert the ordering invariant\n\nOrdering is invisible in code review until someone moves cache above redact.\nAssert the invariant in a test that runs on every commit.\n\n```python\ndef test_cache_key_does_not_leak_pii():\n    \"\"\"P24 — cache key built from REDACTED prompt, not raw.\"\"\"\n    a = redaction_middleware({\"input\": \"Ticket from alice@acme.com\", \"tenant_id\": \"T1\"})\n    b = redaction_middleware({\"input\": \"Ticket from bob@other.com\",  \"tenant_id\": \"T1\"})\n    assert cache_key(a[\"input\"], None, \"T1\") == cache_key(b[\"input\"], None, \"T1\")\n\ndef test_cache_key_tenant_isolation():\n    \"\"\"P24\u002FP33 — same prompt, different tenants, different cache keys.\"\"\"\n    assert cache_key(\"notes\", None, \"T1\") != cache_key(\"notes\", None, \"T2\")\n\ndef test_cache_key_tool_aware():\n    \"\"\"P61 — same prompt, different tool bindings, different cache keys.\"\"\"\n    assert cache_key(\"p\", [{\"name\":\"search\"}], \"T\") != cache_key(\"p\", [{\"name\":\"code_exec\"}], \"T\")\n```\n\nRun in CI. A failure means someone broke the ordering invariant — chain does\nnot merge until it is fixed.\n\n## Output\n\n- Six middleware layers composed in canonical order: redact → guardrail → budget → cache → retry → model\n- Reversible PII redaction with placeholder map (emails, phones, SSNs, credit cards; Presidio optional for names\u002Faddresses)\n- Guardrails middleware with injection-pattern detection and user-content wrapping\n- Per-session \u002F per-tenant token budget with thread-safe counter\n- Cache-key hash that includes prompt + bound-tool schemas + tenant id (fixes P61 and P24)\n- Retry middleware with `request_id` tagging so the token aggregator deduplicates (fixes P25)\n- Integration tests asserting the ordering invariant\n\n## Error Handling\n\n| Error \u002F failure mode | Cause | Fix |\n|---|---|---|\n| Tenant B receives Tenant A's PII on a cache hit | **Cache before redact (P24)** — raw PII went into the cache key | Reorder: redaction runs first; cache key built on redacted prompt + tenant_id |\n| Token-usage aggregator reports 2x actual usage after a retry | **Retry double-count (P25)** — both attempts emit `on_llm_end`, aggregator sums | Attach `request_id` on first attempt; aggregator dedupes by `request_id` |\n| Two chains with different bound tools return same cached response | **P61** — `InMemoryCache()` hashes prompt string only, not tool schemas | Use `cache_key(prompt, bound_tools, tenant_id)` with `blake2b` over all three |\n| Agent loops past 15 iterations on vague prompt; bill spikes | **No token budget (P10)** — `recursion_limit=25` default has no cost ceiling | Insert `budget_middleware` before cache; `raise BudgetExceeded` if session over ceiling |\n| Model follows `\"Ignore previous instructions and...\"` in a RAG doc | **No guardrail (P34)** — `Runnable.invoke` does not sanitize prompt injection | Insert `guardrail_middleware` after redact, before cache; wrap user input in `\u003Cuser_input>` tags |\n| `GuardrailViolation` raised on legitimate prompt | Over-eager injection pattern match | Tune patterns in `references\u002Fordering-invariants.md`; log false positives for iteration |\n| Cache poisoning after a deploy that changed tool schemas | Old cache entries reference old tool list | Bump a `schema_version` constant and include it in the cache key |\n| Budget tracker drift in multi-worker deploy | **P29 analog** — in-process dict is per-worker only | Back `TokenBudget` with Redis or another shared store |\n| Retries still fire on `KeyboardInterrupt` during local dev | **P07** — default `exceptions_to_handle` includes `KeyboardInterrupt` on Python \u003C 3.12 | Explicitly list retryable exceptions; never catch `BaseException` |\n\n## Examples\n\n### Building a chain end-to-end with correct order\n\nThe Step 7 composition shows the six layers in order. In production code this\nusually lives in a factory — `build_chain(tenant_id: str, allowed_tools: set[str])` —\nthat closes over the tenant-scoped cache backend and budget instance. The\nfactory makes the order explicit and testable.\n\n### LangGraph agent version\n\nThe same six layers in a LangGraph agent become six nodes plus conditional\nedges. `budget` routes to `END` on violation; `guardrail` routes to\n`error_handler` on injection match; `cache` routes to `END` on hit. See\n`references\u002Fordering-invariants.md` for the adapted graph topology.\n\n### Debugging a cache-poisoning incident\n\nPost-mortem template: (1) enumerate cache entries, (2) check whether keys were\nbuilt pre- or post-redaction, (3) identify the first cross-tenant hit in logs,\n(4) purge by tenant prefix or full flush, (5) add the ordering integration\ntest from Step 8 so this cannot recur.\n\n## Resources\n\n- [LangChain 1.0 \u002F LangGraph 1.0 release announcement](https:\u002F\u002Fblog.langchain.com\u002Flangchain-langgraph-1dot0\u002F)\n- [LangChain how-to: caching](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fhow_to\u002Fchat_model_caching\u002F)\n- [LangChain callbacks](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fconcepts\u002Fcallbacks\u002F)\n- [LangGraph middleware \u002F pre_model_hook](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Fconcepts\u002Fagentic_concepts\u002F)\n- [Microsoft Presidio (PII detection)](https:\u002F\u002Fmicrosoft.github.io\u002Fpresidio\u002F)\n- [OWASP LLM01: Prompt Injection](https:\u002F\u002Fowasp.org\u002Fwww-project-top-10-for-large-language-model-applications\u002F)\n- Pack pain catalog: `docs\u002Fpain-catalog.md` (entries **P10, P24, P25, P34, P61**, plus P27, P29, P30, P33)\n- Companion references: [ordering-invariants.md](references\u002Fordering-invariants.md), [pii-redaction.md](references\u002Fpii-redaction.md), [cache-key-design.md](references\u002Fcache-key-design.md), [retry-telemetry.md](references\u002Fretry-telemetry.md)\n","# LangChain Middleware Patterns (Python)\n\n## Overview\n\nTenant A sends a prompt: *\"Summarize this support ticket from **alice@acme.com**\nabout her overdue invoice.\"* The chain's caching middleware ran before the PII\nredaction middleware, so the raw prompt — email and all — became part of the\ncache key. Thirty seconds later Tenant B sends a semantically identical prompt\n(different tenant, different customer, same shape). Cache hits. Tenant B's user\ngets back a summary that names `alice@acme.com` and her overdue invoice. That is\npain-catalog entry **P24** in production, and it is a real class of incident —\npost-mortems read like \"we added caching to cut cost, leaked a customer's PII to\na different tenant within an hour.\"\n\nThe sibling failure modes:\n\n- **P25** — Retry middleware runs the model call twice on a 429; both attempts\n  fire `on_llm_end`; the token-usage aggregator sums both; a single logical call\n  bills as two, tenant's per-session budget trips at 50% of true usage.\n- **P10** — Agent loops exceed 15 iterations on vague prompts. There is no\n  default cost cap. A per-session token-budget middleware solves this; without\n  one, a single \"help me with my account\" prompt can burn thousands of tokens.\n- **P34** — `Runnable.invoke` does not sanitize prompt injection. A RAG document\n  containing `\"Ignore previous instructions and...\"` is followed verbatim.\n  Guardrails middleware is your injection defense; without it, indirect prompt\n  injection is a one-line exploit.\n- **P61** — `set_llm_cache(InMemoryCache())` hashes the prompt string only.\n  Two chains with different tool bindings return the same cached response;\n  tools are silently ignored by the cache key.\n\nThis skill defines the canonical middleware order for LangChain 1.0 chains and\nLangGraph 1.0 agents, with an ordering-invariants matrix (every adjacent pair\nhas a named failure mode if you swap them), six reference implementations, a\ncache-key hash that includes prompt **plus bound-tools plus tenant_id**, retry\ntelemetry that deduplicates by `request_id`, and an integration test pattern\nthat asserts the ordering invariant on every build.\n\nPin: `langchain-core 1.0.x`, `langchain 1.0.x`, `langgraph 1.0.x`. Pain-catalog\nanchors: **P10, P24, P25, P34, P61**, with supporting references to P27, P29,\nP30, P33.\n\n## Prerequisites\n\n- Python 3.10+\n- `langchain-core >= 1.0, \u003C 2.0`\n- `langgraph >= 1.0, \u003C 2.0` (for agent middleware)\n- At least one provider package: `pip install langchain-anthropic` (or openai)\n- Optional: `presidio-analyzer` + `presidio-anonymizer` for PII NER beyond regex\n- Optional: `redis` + `langchain-redis` for multi-worker cache and rate limiting\n\n## Instructions\n\n### Step 1 — Adopt the canonical middleware order\n\nEvery LangChain 1.0 chain and LangGraph 1.0 agent that goes to production\napplies middleware in this order:\n\n```\nuser → redact → guardrail → budget → cache → retry → model\n```\n\n- **redact → cache (P24):** cache key must be PII-free or Tenant A's PII leaks to Tenant B on a hit\n- **guardrail → cache:** an injection-laden prompt must never become a cache entry\n- **budget → cache:** cache hits count against RPS; check budget first so loops cannot DoS a session on hits alone\n- **cache → retry:** cache hits bypass retry; retry wraps only the model call\n\nProduction chains typically run **4-6 middleware layers** with **\u003C1ms per\nlayer** overhead (bench: p50 0.3ms\u002Flayer, p99 0.9ms on a 100-request sample).\nSee [ordering-invariants.md](references\u002Fordering-invariants.md) for the full\npairwise matrix and the benchmark script.\n\n### Step 2 — PII redaction middleware\n\nMask entities with reversible placeholders so the caller can reinsert in the\noutput — but the cache key and the model prompt only ever see redacted text.\n\n```python\nimport re\nfrom typing import Any\n\n_REDACTORS = [\n    (\"EMAIL\", re.compile(r\"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\")),\n    (\"PHONE\", re.compile(r\"\\+?\\d[\\d\\s\\-\\(\\)]{7,}\\d\")),\n    (\"SSN\",   re.compile(r\"\\b\\d{3}-\\d{2}-\\d{4}\\b\")),\n    (\"CC\",    re.compile(r\"\\b(?:\\d[ -]*?){13,16}\\b\")),\n]\n\ndef redact(text: str) -> tuple[str, dict[str, str]]:\n    pmap: dict[str, str] = {}\n    for label, pattern in _REDACTORS:\n        for i, match in enumerate(pattern.findall(text)):\n            token = f\"\u003C{label}_{i}>\"\n            pmap[token] = match\n            text = text.replace(match, token)\n    return text, pmap\n\ndef redaction_middleware(inputs: dict[str, Any]) -> dict[str, Any]:\n    redacted, pmap = redact(inputs[\"input\"])\n    return {**inputs, \"input\": redacted, \"_pii_map\": pmap}\n```\n\nFor names, addresses, and custom entities, Presidio's `AnalyzerEngine` covers\n20+ entity types. See [pii-redaction.md](references\u002Fpii-redaction.md) for the\nregex vs spaCy vs Presidio tradeoff matrix, GDPR\u002FHIPAA\u002FPCI-DSS entity lists,\nand the reinsertion pattern (return un-redacted output **only** to the\noriginating tenant — never cross-populate).\n\n### Step 3 — Guardrails middleware\n\nDetect injection patterns up front and wrap user content so the model treats\nit as data. Two layers: pattern match (catches the 90% case cheaply) plus\nprompt wrapping (neutralizes what slips through).\n\n```python\nINJECTION_PATTERNS = [\n    re.compile(r\"ignore (all |the )?(previous|prior|above) (instructions|rules)\", re.I),\n    re.compile(r\"system prompt (is|was|now)\", re.I),\n    re.compile(r\"you are now (a |an )?\", re.I),\n    re.compile(r\"\u003C\u002F?(system|instruction|prompt)>\", re.I),\n]\n\nclass GuardrailViolation(Exception):\n    pass\n\ndef guardrail_middleware(inputs: dict[str, Any],\n                        allowed_tools: set[str] | None = None) -> dict[str, Any]:\n    for pattern in INJECTION_PATTERNS:\n        if pattern.search(inputs[\"input\"]):\n            raise GuardrailViolation(f\"Injection pattern matched: {pattern.pattern!r}\")\n    wrapped = f\"\u003Cuser_input>\\n{inputs['input']}\\n\u003C\u002Fuser_input>\"\n    out = {**inputs, \"input\": wrapped}\n    if allowed_tools is not None:\n        out[\"_tool_allowlist\"] = allowed_tools\n    return out\n```\n\nNever rely on the model to \"know what is an instruction\" without wrapping.\n\n### Step 4 — Token-budget middleware (per-session \u002F per-tenant)\n\nDirectly addresses P10 — agents loop 15+ iterations on vague prompts and burn\nthousands of tokens. The budget middleware raises before the model call if\nthe session is over ceiling.\n\n```python\nfrom dataclasses import dataclass, field\nfrom collections import defaultdict\nfrom threading import Lock\n\nclass BudgetExceeded(Exception): pass\n\n@dataclass\nclass TokenBudget:\n    ceiling: int = 50_000           # tokens per session\n    _usage: dict[str, int] = field(default_factory=lambda: defaultdict(int))\n    _lock: Lock = field(default_factory=Lock)\n\n    def record(self, session_id: str, tokens: int) -> None:\n        with self._lock:\n            self._usage[session_id] += tokens\n\n    def check(self, session_id: str) -> None:\n        with self._lock:\n            used = self._usage[session_id]\n        if used >= self.ceiling:\n            raise BudgetExceeded(f\"Session {session_id}: {used}\u002F{self.ceiling}\")\n\nbudget = TokenBudget(ceiling=50_000)\n\ndef budget_middleware(inputs: dict[str, Any]) -> dict[str, Any]:\n    budget.check(inputs.get(\"session_id\") or \"anonymous\")\n    return inputs\n```\n\nPair with a `BaseCallbackHandler.on_llm_end` that calls `budget.record(...)`\nwith `usage_metadata.input_tokens + output_tokens`. For multi-worker deploys,\nback `TokenBudget` with Redis — per-process dicts are per-process (P29).\n\n### Step 5 — Caching middleware with tool-aware key\n\nP61 is the booby trap: `InMemoryCache()` hashes the prompt string only, so\ntwo chains with different tool lists return the same cached response. Use a\ncustom key over **prompt + bound tools + tenant id**.\n\n```python\nimport hashlib, json\nfrom typing import Callable\n\ndef cache_key(prompt: str, bound_tools: list[dict] | None, tenant_id: str) -> str:\n    \"\"\"Blake2b-16 hash. Tool-aware, tenant-aware, collision-safe via \\\\x1f separator.\"\"\"\n    h = hashlib.blake2b(digest_size=16)\n    h.update(prompt.encode(\"utf-8\")); h.update(b\"\\x1f\")\n    if bound_tools:\n        h.update(json.dumps(bound_tools, sort_keys=True).encode(\"utf-8\"))\n    h.update(b\"\\x1f\"); h.update(tenant_id.encode(\"utf-8\"))\n    return h.hexdigest()\n\ndef cache_middleware(get: Callable[[str], Any | None], put: Callable[[str, Any], None]):\n    def _run(inputs: dict[str, Any]) -> dict[str, Any]:\n        key = cache_key(inputs[\"input\"], inputs.get(\"_bound_tools\"),\n                        inputs.get(\"tenant_id\", \"default\"))\n        hit = get(key)\n        if hit is not None:\n            return {**inputs, \"_cache_hit\": True, \"output\": hit}\n        inputs[\"_cache_key\"] = key\n        return inputs\n    return _run\n```\n\nThe cache key **must** be computed on the redacted prompt (Step 2 ran first)\nand **must** include the tool schemas. See\n[cache-key-design.md](references\u002Fcache-key-design.md) for backend comparison\n(`InMemoryCache` \u002F `SQLiteCache` \u002F `RedisCache` \u002F `RedisSemanticCache`),\ninvalidation strategies (TTL, schema-version bump, tenant-wide purge), and\nthe full pitfalls list including Unicode normalization and P62.\n\n### Step 6 — Retry middleware with telemetry tagging\n\nP25: retry runs the model call twice on a 429, both attempts emit\n`on_llm_end`, the aggregator sums both, tenant budget trips at 50% of true\nusage. Fix: attach a stable `request_id` on the first attempt, and have the\naggregator **replace** (not add) per `request_id` so only the last successful\nattempt is counted.\n\n```python\nimport time, uuid\n\nRETRYABLE = (TimeoutError, ConnectionError,\n             # Provider-specific — import from your provider SDK:\n             # anthropic.RateLimitError, anthropic.APITimeoutError,\n             # openai.RateLimitError, openai.APITimeoutError,\n             )\n\ndef retry_middleware(max_retries: int = 2, base_delay: float = 1.0):\n    def _run(inputs: dict[str, Any]) -> dict[str, Any]:\n        request_id = inputs.get(\"request_id\") or str(uuid.uuid4())\n        return {**inputs, \"request_id\": request_id}\n    return _run\n```\n\nSee [retry-telemetry.md](references\u002Fretry-telemetry.md) for the full retry\nloop, the dedup-by-`request_id` aggregator, provider-specific retryable\nexception lists (Anthropic \u002F OpenAI \u002F Gemini), exponential backoff with\njitter, and a circuit breaker that stops retry storms on a dead upstream.\n\n### Step 7 — Compose the middleware into a chain\n\n```python\nfrom langchain_core.runnables import RunnableLambda, RunnablePassthrough\n\n# Order matters. See Step 1 for why.\nchain = (\n    RunnableLambda(redaction_middleware)\n    | RunnableLambda(guardrail_middleware)\n    | RunnableLambda(budget_middleware)\n    | RunnableLambda(cache_middleware(cache_get, cache_put))\n    | RunnableLambda(retry_middleware(max_retries=2))\n    | model                             # ChatAnthropic \u002F ChatOpenAI\n)\n```\n\nFor LangGraph agents, the same layers apply but are wired as **nodes with\nconditional edges** — a `budget` node that routes to `END` on violation, a\n`guardrail` node that routes to an error handler on injection match, and so on.\nSee the LangGraph adaptation in `references\u002Fordering-invariants.md`.\n\n### Step 8 — Integration test: assert the ordering invariant\n\nOrdering is invisible in code review until someone moves cache above redact.\nAssert the invariant in a test that runs on every commit.\n\n```python\ndef test_cache_key_does_not_leak_pii():\n    \"\"\"P24 — cache key built from REDACTED prompt, not raw.\"\"\"\n    a = redaction_middleware({\"input\": \"Ticket from alice@acme.com\", \"tenant_id\": \"T1\"})\n    b = redaction_middleware({\"input\": \"Ticket from bob@other.com\",  \"tenant_id\": \"T1\"})\n    assert cache_key(a[\"input\"], None, \"T1\") == cache_key(b[\"input\"], None, \"T1\")\n\ndef test_cache_key_tenant_isolation():\n    \"\"\"P24\u002FP33 — same prompt, different tenants, different cache keys.\"\"\"\n    assert cache_key(\"notes\", None, \"T1\") != cache_key(\"notes\", None, \"T2\")\n\ndef test_cache_key_tool_aware():\n    \"\"\"P61 — same prompt, different tool bindings, different cache keys.\"\"\"\n    assert cache_key(\"p\", [{\"name\":\"search\"}], \"T\") != cache_key(\"p\", [{\"name\":\"code_exec\"}], \"T\")\n```\n\nRun in CI. A failure means someone broke the ordering invariant — chain does\nnot merge until it is fixed.\n\n## Output\n\n- Six middleware layers composed in canonical order: redact → guardrail → budget → cache → retry → model\n- Reversible PII redaction with placeholder map (emails, phones, SSNs, credit cards; Presidio optional for names\u002Faddresses)\n- Guardrails middleware with injection-pattern detection and user-content wrapping\n- Per-session \u002F per-tenant token budget with thread-safe counter\n- Cache-key hash that includes prompt + bound-tool schemas + tenant id (fixes P61 and P24)\n- Retry middleware with `request_id` tagging so the token aggregator deduplicates (fixes P25)\n- Integration tests asserting the ordering invariant\n\n## Error Handling\n\n| Error \u002F failure mode | Cause | Fix |\n|---|---|---|\n| Tenant B receives Tenant A's PII on a cache hit | **Cache before redact (P24)** — raw PII went into the cache key | Reorder: redaction runs first; cache key built on redacted prompt + tenant_id |\n| Token-usage aggregator reports 2x actual usage after a retry | **Retry double-count (P25)** — both attempts emit `on_llm_end`, aggregator sums | Attach `request_id` on first attempt; aggregator dedupes by `request_id` |\n| Two chains with different bound tools return same cached response | **P61** — `InMemoryCache()` hashes prompt string only, not tool schemas | Use `cache_key(prompt, bound_tools, tenant_id)` with `blake2b` over all three |\n| Agent loops past 15 iterations on vague prompt; bill spikes | **No token budget (P10)** — `recursion_limit=25` default has no cost ceiling | Insert `budget_middleware` before cache; `raise BudgetExceeded` if session over ceiling |\n| Model follows `\"Ignore previous instructions and...\"` in a RAG doc | **No guardrail (P34)** — `Runnable.invoke` does not sanitize prompt injection | Insert `guardrail_middleware` after redact, before cache; wrap user input in `\u003Cuser_input>` tags |\n| `GuardrailViolation` raised on legitimate prompt | Over-eager injection pattern match | Tune patterns in `references\u002Fordering-invariants.md`; log false positives for iteration |\n| Cache poisoning after a deploy that changed tool schemas | Old cache entries reference old tool list | Bump a `schema_version` constant and include it in the cache key |\n| Budget tracker drift in multi-worker deploy | **P29 analog** — in-process dict is per-worker only | Back `TokenBudget` with Redis or another shared store |\n| Retries still fire on `KeyboardInterrupt` during local dev | **P07** — default `exceptions_to_handle` includes `KeyboardInterrupt` on Python \u003C 3.12 | Explicitly list retryable exceptions; never catch `BaseException` |\n\n## Examples\n\n### Building a chain end-to-end with correct order\n\nThe Step 7 composition shows the six layers in order. In production code this\nusually lives in a factory — `build_chain(tenant_id: str, allowed_tools: set[str])` —\nthat closes over the tenant-scoped cache backend and budget instance. The\nfactory makes the order explicit and testable.\n\n### LangGraph agent version\n\nThe same six layers in a LangGraph agent become six nodes plus conditional\nedges. `budget` routes to `END` on violation; `guardrail` routes to\n`error_handler` on injection match; `cache` routes to `END` on hit. See\n`references\u002Fordering-invariants.md` for the adapted graph topology.\n\n### Debugging a cache-poisoning incident\n\nPost-mortem template: (1) enumerate cache entries, (2) check whether keys were\nbuilt pre- or post-redaction, (3) identify the first cross-tenant hit in logs,\n(4) purge by tenant prefix or full flush, (5) add the ordering integration\ntest from Step 8 so this cannot recur.\n\n## Resources\n\n- [LangChain 1.0 \u002F LangGraph 1.0 release announcement](https:\u002F\u002Fblog.langchain.com\u002Flangchain-langgraph-1dot0\u002F)\n- [LangChain how-to: caching](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fhow_to\u002Fchat_model_caching\u002F)\n- [LangChain callbacks](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fconcepts\u002Fcallbacks\u002F)\n- [LangGraph middleware \u002F pre_model_hook](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Fconcepts\u002Fagentic_concepts\u002F)\n- [Microsoft Presidio (PII detection)](https:\u002F\u002Fmicrosoft.github.io\u002Fpresidio\u002F)\n- [OWASP LLM01: Prompt Injection](https:\u002F\u002Fowasp.org\u002Fwww-project-top-10-for-large-language-model-applications\u002F)\n- Pack pain catalog: `docs\u002Fpain-catalog.md` (entries **P10, P24, P25, P34, P61**, plus P27, P29, P30, P33)\n- Companion references: [ordering-invariants.md](references\u002Fordering-invariants.md), [pii-redaction.md](references\u002Fpii-redaction.md), [cache-key-design.md](references\u002Fcache-key-design.md), [retry-telemetry.md](references\u002Fretry-telemetry.md)\n",{"name":5,"tags":24,"author":33,"license":15,"version":34,"description":35,"allowed-tools":36,"compatible-with":37},[25,26,27,28,29,30,31,32],"saas","langchain","langgraph","python","langchain-1.0","middleware","security","caching","Jeremy Longshore \u003Cjeremy@intentsolutions.io>","2.0.0","Build composable middleware for LangChain 1.0 chains and LangGraph 1.0 agents —\nPII redaction, caching, retry, token budgets, guardrails — with ORDERING rules\nthat avoid cache-key leakage and double-counting. Use when adding cross-cutting\nbehavior, hardening against prompt injection, enforcing per-tenant budgets, or\ndebugging cache-poisoning incidents.\nTrigger with \"langchain middleware\", \"langgraph middleware\", \"PII redaction\nmiddleware\", \"cache middleware order\", \"langchain guardrails\".\n","Read, Write, Edit, Bash(python:*)","claude-code, codex","main","99825ad3f3bcc6597ddcc7294a14e6e922f2b67b","skills\u002Fsaas-packs--langchain-py-pack--langchain-middleware-patterns",0,"https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills","https:\u002F\u002Fgithub.com\u002Fjukeyman","https:\u002F\u002FRJBUSINESSSOLUTIONS.ORG","Credit and Finance Expert | Developer\r\n\r\nI'm Rick Jefferson, a seasoned credit and finance expert with over a decade of experience in financial literacy,","2026-07-13 07:03:29",{"source":8,"skillName":5,"commands":48,"prompt":58,"zipAvailable":59},[49,52,55],{"tool":50,"command":51},"npx","npx skills add jukeyman\u002Fjukeyman-skills --skill langchain-middleware-patterns",{"tool":53,"command":54},"bunx","bunx skills add jukeyman\u002Fjukeyman-skills --skill langchain-middleware-patterns",{"tool":56,"command":57},"pnpm","pnpm dlx skills add jukeyman\u002Fjukeyman-skills --skill langchain-middleware-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--langchain-py-pack--langchain-middleware-patterns\u002FSKILL.md",true,[],[62,69,76,83,90,98],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M79ANS2SM329NEP5ZCX106RR","zustand-store-creator","Create zustand store creator operations. Auto-activating skill for Frontend Development.\nTriggers on: zustand store creator, zustand store creator\nPart of the Frontend Development skill category. Use when working with zustand store creator functionality. Trigger with phrases like \"zustand store creator\", \"zustand creator\", \"zustand\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzustand-store-creator\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M79AMZKP4YDEZ7EHG1Y7PP74","zero-trust-config-helper","Configure with zero trust config helper operations. Auto-activating skill for Security Advanced.\nTriggers on: zero trust config helper, zero trust config helper\nPart of the Security Advanced skill category. Use when configuring systems or services. Trigger with phrases like \"zero trust config helper\", \"zero helper\", \"zero\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzero-trust-config-helper\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M79AMJSBCEJQNBTYNAHYN5HM","zapier-integration-helper","Assist with zapier integration helper operations. Auto-activating skill for Business Automation.\nTriggers on: zapier integration helper, zapier integration helper\nPart of the Business Automation skill category. Use when working with APIs or building integrations. Trigger with phrases like \"zapier integration helper\", \"zapier helper\", \"zapier\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzapier-integration-helper\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M79AHJZGVMARS13VFQYRR1MP","yaml-config-validator","Validate yaml config validator operations. Auto-activating skill for DevOps Basics.\nTriggers on: yaml config validator, yaml config validator\nPart of the DevOps Basics skill category. Use when configuring systems or services. Trigger with phrases like \"yaml config validator\", \"yaml validator\", \"yaml\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fyaml-config-validator\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":94,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":19},"01M79AHGDZRN0020RDQSQDPAM8","xvary-stock-research","Thesis-driven equity analysis from public SEC EDGAR and market data; \u002Fanalyze, \u002Fscore, \u002Fcompare workflows with bundled Python tools (Claude Code, Cursor, Codex).","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FSKILL.md",[],[],{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":19},"01M79AHCYJ9FV9RMHQ24HDRN33","xss-vulnerability-scanner","Scan xss vulnerability scanner operations. Auto-activating skill for Security Fundamentals.\nTriggers on: xss vulnerability scanner, xss vulnerability scanner\nPart of the Security Fundamentals skill category. Use when working with xss vulnerability scanner functionality. Trigger with phrases like \"xss vulnerability scanner\", \"xss scanner\", \"xss\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxss-vulnerability-scanner\u002FSKILL.md",[],[]]