[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M792F3DG8CZ6FH754ZP85FGN":3,"skill-same:01M792F3DG8CZ6FH754ZP85FGN":60},{"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":37,"commitSha":38,"skillDirectory":39,"forksCount":40,"repositoryHtmlUrl":41,"repositoryHomepageUrl":6,"ownerHtmlUrl":42,"ownerBlogUrl":43,"ownerDescription":44,"updatedAt":45,"install":46,"resources":59},"01M792F3DG8CZ6FH754ZP85FGN","langchain-sdk-patterns",null,"Compose LangChain 1.0 Python runnables with the production defaults the docs\ndo not warn about: parallel batching, narrow fallbacks, and brace-safe prompts.\nUse when building an LCEL chain with RunnableSequence \u002F RunnableParallel,\nadding resilience via `.with_fallbacks()`, tuning throughput with `.batch()`\nor `.abatch()`, or wrapping user input in a prompt template.\nTrigger with \"langchain runnable\", \"with_fallbacks\", \"langchain batch\",\n\"runnable sequence\", \"lcel\", \"runnableparallel\", \"chain composition\".","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-sdk-patterns\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: langchain-sdk-patterns\ndescription: |\n  Compose LangChain 1.0 Python runnables with the production defaults the docs\n  do not warn about: parallel batching, narrow fallbacks, and brace-safe prompts.\n  Use when building an LCEL chain with RunnableSequence \u002F RunnableParallel,\n  adding resilience via `.with_fallbacks()`, tuning throughput with `.batch()`\n  or `.abatch()`, or wrapping user input in a prompt template.\n  Trigger with \"langchain runnable\", \"with_fallbacks\", \"langchain batch\",\n  \"runnable sequence\", \"lcel\", \"runnableparallel\", \"chain composition\".\nallowed-tools: Read, Write, Edit, Bash(python:*), Bash(pip:*)\nversion: 2.0.0\nlicense: MIT\nauthor: Jeremy Longshore \u003Cjeremy@intentsolutions.io>\ntags: [saas, langchain, langgraph, python, langchain-1.0, lcel, runnables]\ncompatible-with: claude-code, codex\n---\n\n# LangChain SDK Patterns (Python)\n\n## Overview\n\n`chain.batch(inputs)` in LangChain 1.0 does **not** parallelize by default. The\n`max_concurrency` parameter defaults to **1** in several provider packages\n(notably older `langchain-openai`), so a call like `chain.batch(inputs_1000)`\nruns 1,000 sequential round-trips — same wall-clock time as a `for` loop, plus\nthe overhead of the batch machinery. Users file \"batch is slow\" tickets,\nbenchmark it against asyncio, and move to a different framework — when the fix\nis two lines:\n\n```python\n# BAD — silently serializes (P08)\nchain.batch(inputs_1000)\n\n# GOOD — 10 in flight at once\nchain.batch(inputs_1000, config={\"max_concurrency\": 10})\n```\n\nThen three more traps wait:\n\n- **P07** — `.with_fallbacks([backup])` defaults `exceptions_to_handle=(Exception,)`,\n  and on Python \u003C3.12 that tuple includes `KeyboardInterrupt`. A `Ctrl+C` during\n  a long run does not stop the process — it silently hands off to the fallback\n  chain and keeps billing.\n- **P57** — `ChatPromptTemplate.from_messages(..., template_format=\"f-string\")`\n  (the default) parses every `{` in every string, including user input. A user\n  who pastes `{\"error\": \"...\"}` raises `KeyError: 'error'` at invoke time.\n- **P53** — Pydantic v2 rejects extra fields by default; models cheerfully add\n  `summary` or `confidence` to your `Plan` schema and `with_structured_output`\n  crashes with `ValidationError: extra fields not permitted`.\n\nThis skill walks through LCEL composition (`RunnableSequence`, `RunnableParallel`,\n`RunnableBranch`, `RunnablePassthrough`, `RunnableLambda`); the correct\n`exceptions_to_handle` whitelist per provider; `max_concurrency` tuning with\nsafe ceilings (10 for most providers, 20+ with a semaphore); and prompt\ntemplates that survive untrusted input. Pin: `langchain-core 1.0.x`,\n`langchain-anthropic 1.0.x`, `langchain-openai 1.0.x`. Pain-catalog anchors:\nP07, P08, P53, P57.\n\n## Prerequisites\n\n- Python 3.10+ (3.12+ fixes the `KeyboardInterrupt` half of P07 — upgrade if you can)\n- `langchain-core >= 1.0, \u003C 2.0`\n- At least one provider: `pip install langchain-anthropic langchain-openai`\n- `pydantic >= 2.0` for schema-aware composition\n- Completed `langchain-model-inference` — the chat-model factory from that skill is reused here\n\n## Instructions\n\n### Step 1 — Compose with typed runnables, not lambdas\n\n```python\nfrom langchain_anthropic import ChatAnthropic\nfrom langchain_core.prompts import ChatPromptTemplate\nfrom langchain_core.output_parsers import StrOutputParser\nfrom langchain_core.runnables import RunnableParallel, RunnablePassthrough\n\nllm = ChatAnthropic(model=\"claude-sonnet-4-6\", timeout=30, max_retries=2)\n\nprompt = ChatPromptTemplate.from_messages(\n    [(\"system\", \"You are a summarizer.\"), (\"human\", \"{text}\")],\n    template_format=\"jinja2\",  # P57 — see Step 4\n)\n\n# Sequence: prompt -> llm -> str\nchain = prompt | llm | StrOutputParser()\n\n# Parallel: run two sub-chains and merge\nenriched = RunnableParallel(\n    summary=chain,\n    original=RunnablePassthrough(),\n)\n```\n\nThe `|` operator creates a `RunnableSequence`. Each step has a declared input\nand output shape — swap a concrete model for a router and the type contract\nholds. See [Runnable Composition Matrix](references\u002Frunnable-composition-matrix.md)\nfor when to reach for `RunnableSequence` vs `RunnableParallel` vs `RunnableBranch`\nvs `RunnableLambda`, with input\u002Foutput shape conventions for each.\n\n### Step 2 — Add fallbacks with a narrow exception whitelist\n\n```python\nfrom anthropic import APIError, APITimeoutError, RateLimitError\nfrom langchain_openai import ChatOpenAI\n\nbackup = ChatOpenAI(model=\"gpt-4o\", timeout=30, max_retries=2)\nbackup_chain = prompt | backup | StrOutputParser()\n\n# GOOD — only retry on transient provider errors\nresilient = chain.with_fallbacks(\n    [backup_chain],\n    exceptions_to_handle=(RateLimitError, APIError, APITimeoutError),\n)\n\n# BAD — default `(Exception,)` catches KeyboardInterrupt on Python \u003C3.12 (P07)\n# resilient_bad = chain.with_fallbacks([backup_chain])\n```\n\nThe default `exceptions_to_handle=(Exception,)` on Python \u003C3.12 inherits\n`KeyboardInterrupt` and `SystemExit` into the caught set — which means a\n`Ctrl+C` during a long `.batch()` run falls through to the backup instead of\nstopping. Python 3.12+ moved these under `BaseException` directly, which fixes\nthe inheritance path, but the default is still too broad: a Pydantic\n`ValidationError` or a `ToolException` will trigger a pointless backup call.\nSee [Fallback Exception List](references\u002Ffallback-exception-list.md) for the\ncurated whitelist per provider with concrete imports.\n\n### Step 3 — Batch with explicit concurrency\n\n```python\nimport asyncio\n\ninputs = [{\"text\": doc} for doc in documents]\n\n# Synchronous batch — blocks until done\nresults = chain.batch(inputs, config={\"max_concurrency\": 10})\n\n# Async batch — non-blocking\nresults = await chain.abatch(inputs, config={\"max_concurrency\": 10})\n```\n\nSafe ceilings: **10** for Anthropic and OpenAI at default tier; **20+** only\nbehind an `asyncio.Semaphore` if you are also tracking rate-limit headers.\nClaude TPM\u002FRPM limits vary by tier; OpenAI's TPD (tokens per day) is the\nbinding limit at scale. See [Batch Concurrency Tuning](references\u002Fbatch-concurrency-tuning.md)\nfor per-provider ceilings and the semaphore pattern.\n\n`invoke` vs `batch` vs `stream` — when each is correct:\n\n| Method | Input shape | Concurrency | Error behavior | When to use |\n|---|---|---|---|---|\n| `.invoke(x)` | Single | 1 | Raises on failure | One-shot call, interactive, tests |\n| `.batch(xs, config={\"max_concurrency\": N})` | List | N parallel | Raises on first failure unless `return_exceptions=True` | Bulk sync workloads, ETL, eval harnesses |\n| `.abatch(xs, config={\"max_concurrency\": N})` | List | N parallel (async) | Same as `.batch` | Event loops, async web servers, LangGraph nodes |\n| `.stream(x)` | Single | 1, chunked | Raises on failure | Interactive UI, live token display |\n| `.astream(x)` \u002F `.astream_events(x, version=\"v2\")` | Single | 1, chunked (async) | Raises on failure | Async UIs, event-driven pipelines, token metering (see `langchain-model-inference`) |\n\nPass `return_exceptions=True` in the config to keep a batch from aborting on\nthe first failure — exceptions come back in the result list instead of raising.\n\n### Step 4 — Escape prompt templates for untrusted input\n\n```python\nfrom langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n\n# BAD — default f-string format crashes on literal `{` in user input (P57)\nbad = ChatPromptTemplate.from_messages(\n    [(\"system\", \"Reply in JSON\"), (\"human\", \"{user_text}\")]\n)\nbad.invoke({\"user_text\": '{\"error\": \"oops\"}'})  # KeyError: 'error'\n\n# GOOD — jinja2 treats `{...}` as literal, uses `{{ var }}` for substitution\ngood = ChatPromptTemplate.from_messages(\n    [(\"system\", \"Reply in JSON\"), (\"human\", \"{{ user_text }}\")],\n    template_format=\"jinja2\",\n)\ngood.invoke({\"user_text\": '{\"error\": \"oops\"}'})  # OK\n\n# MIXED — message history is a list, use MessagesPlaceholder\nwith_history = ChatPromptTemplate.from_messages([\n    (\"system\", \"You are a helpful assistant.\"),\n    MessagesPlaceholder(\"history\"),\n    (\"human\", \"{{ question }}\"),\n], template_format=\"jinja2\")\n```\n\nRule of thumb: if any variable can contain user-provided free text (a paste,\na transcript, a code block), use `template_format=\"jinja2\"`. The f-string\nformat is fine for trusted template authors composing fixed instructions, but\nit is the wrong tool for user input. See [Prompt Template Escaping](references\u002Fprompt-template-escaping.md)\nfor the full brace-escaping rules and a `MessagesPlaceholder` reference.\n\n### Step 5 — Validate structured output with `extra=\"ignore\"`\n\n```python\nfrom pydantic import BaseModel, ConfigDict, Field\n\nclass Plan(BaseModel):\n    # P53 — without this, the chain crashes when the model adds extra fields\n    model_config = ConfigDict(extra=\"ignore\")\n    steps: list[str] = Field(default_factory=list)\n    estimated_minutes: int\n\nstructured_chain = prompt | llm.with_structured_output(Plan, method=\"json_schema\")\n```\n\nPydantic v2 rejects unknown fields by default. Models trained on \"be helpful\"\nadd `summary`, `confidence`, `rationale` — the schema crashes instead of\ndropping them. `extra=\"ignore\"` is the right default for model outputs.\n\n## Output\n\n- `RunnableSequence` \u002F `RunnableParallel` composition with declared input\u002Foutput shapes\n- `.with_fallbacks(exceptions_to_handle=(...))` with a narrow, provider-specific whitelist\n- `.batch()` \u002F `.abatch()` with explicit `max_concurrency` (10 default, 20+ behind semaphore)\n- `ChatPromptTemplate.from_messages(..., template_format=\"jinja2\")` for any template touching user input\n- Pydantic schemas with `ConfigDict(extra=\"ignore\")` for structured output\n- A clear `invoke` \u002F `batch` \u002F `abatch` \u002F `stream` \u002F `astream` decision matrix for each chain stage\n\n## Error Handling\n\n| Error | Cause | Fix |\n|-------|-------|-----|\n| `Ctrl+C` does not stop a long `.batch()`; fallback keeps running | `exceptions_to_handle=(Exception,)` swallows `KeyboardInterrupt` on Python \u003C3.12 (P07) | Pass a narrow tuple: `exceptions_to_handle=(RateLimitError, APIError, APITimeoutError)` |\n| `.batch(inputs)` takes same time as sequential loop | `max_concurrency` defaults to 1 (P08) | `config={\"max_concurrency\": 10}`; raise to 20+ only with a semaphore |\n| `KeyError: '\u003Csome-token>'` when invoking a `ChatPromptTemplate` | f-string parser reads user input's `{` as a variable (P57) | `template_format=\"jinja2\"`; escape literals as `{{`\u002F`}}` in f-string mode |\n| `ValidationError: extra fields not permitted` on structured output | Pydantic v2 strict-by-default (P53) | `model_config = ConfigDict(extra=\"ignore\")` on the schema |\n| `ValidationError` caught by fallback and treated as transient | Fallback whitelist too broad | Remove `ValidationError` from `exceptions_to_handle` so it surfaces |\n| `.batch` aborts on the first failure, losing all results | Default raises on first error | Pass `config={\"max_concurrency\": 10, \"return_exceptions\": True}` and filter |\n| Fallback chain never fires even on genuine `RateLimitError` | Provider's own `max_retries` consumes the error first | Lower `max_retries=0` on the primary when a fallback chain is the retry strategy |\n\n## Examples\n\n### Fan-out enrichment with RunnableParallel\n\nA common pattern — given a document, produce a summary, extracted entities,\nand sentiment in parallel. `RunnableParallel` runs sub-chains concurrently and\nmerges results into a dict. Combined with `.batch()` at the outer level, you\nget N documents times 3 sub-chains in flight up to `max_concurrency`.\n\nSee [Runnable Composition Matrix](references\u002Frunnable-composition-matrix.md)\nfor the fan-out\u002Ffan-in pattern and the input\u002Foutput shape of each runnable type.\n\n### Resilient chain with per-provider fallback\n\nPrimary: Claude Sonnet 4.6. Fallback: GPT-4o. Catch only `RateLimitError`,\n`APIError`, and `APITimeoutError` from each SDK — let `AuthenticationError`\nand `ValidationError` crash the process so they get debugged, not masked.\n\nSee [Fallback Exception List](references\u002Ffallback-exception-list.md) for the\nconcrete imports per provider and a note on why `BadRequestError` should not\nbe in the whitelist.\n\n### High-throughput batch with semaphore-bounded concurrency\n\nAt N >= 20 concurrent in-flight calls, provider rate-limit headers become the\nbottleneck. Wrap `.abatch()` in an `asyncio.Semaphore` and honor the\n`retry-after` header on 429 responses.\n\nSee [Batch Concurrency Tuning](references\u002Fbatch-concurrency-tuning.md) for the\nsemaphore pattern and a table of provider TPM\u002FRPM limits per tier.\n\n### Prompt template over user-pasted JSON payload\n\nSupport ticket triage where users paste arbitrary JSON from their app's error\nlog. Without `template_format=\"jinja2\"`, every single ticket with a JSON body\ncrashes the chain at template-render time.\n\nSee [Prompt Template Escaping](references\u002Fprompt-template-escaping.md) for the\nworked example and the `MessagesPlaceholder` pattern for chat history.\n\n## Resources\n\n- [LangChain Python: Runnable interface](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fconcepts\u002Frunnables\u002F)\n- [LangChain Python: `with_fallbacks`](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fhow_to\u002Ffallbacks\u002F)\n- [LangChain Python: `batch` and `abatch`](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fhow_to\u002Fparallel\u002F)\n- [`ChatPromptTemplate` reference](https:\u002F\u002Fpython.langchain.com\u002Fapi_reference\u002Fcore\u002Fprompts\u002Flangchain_core.prompts.chat.ChatPromptTemplate.html)\n- [Pydantic v2 `ConfigDict`](https:\u002F\u002Fdocs.pydantic.dev\u002Flatest\u002Fapi\u002Fconfig\u002F)\n- [LangChain 1.0 release notes](https:\u002F\u002Fblog.langchain.com\u002Flangchain-langgraph-1dot0\u002F)\n- Pack pain catalog: `docs\u002Fpain-catalog.md` (entries P07, P08, P53, P57)\n","# LangChain SDK Patterns (Python)\n\n## Overview\n\n`chain.batch(inputs)` in LangChain 1.0 does **not** parallelize by default. The\n`max_concurrency` parameter defaults to **1** in several provider packages\n(notably older `langchain-openai`), so a call like `chain.batch(inputs_1000)`\nruns 1,000 sequential round-trips — same wall-clock time as a `for` loop, plus\nthe overhead of the batch machinery. Users file \"batch is slow\" tickets,\nbenchmark it against asyncio, and move to a different framework — when the fix\nis two lines:\n\n```python\n# BAD — silently serializes (P08)\nchain.batch(inputs_1000)\n\n# GOOD — 10 in flight at once\nchain.batch(inputs_1000, config={\"max_concurrency\": 10})\n```\n\nThen three more traps wait:\n\n- **P07** — `.with_fallbacks([backup])` defaults `exceptions_to_handle=(Exception,)`,\n  and on Python \u003C3.12 that tuple includes `KeyboardInterrupt`. A `Ctrl+C` during\n  a long run does not stop the process — it silently hands off to the fallback\n  chain and keeps billing.\n- **P57** — `ChatPromptTemplate.from_messages(..., template_format=\"f-string\")`\n  (the default) parses every `{` in every string, including user input. A user\n  who pastes `{\"error\": \"...\"}` raises `KeyError: 'error'` at invoke time.\n- **P53** — Pydantic v2 rejects extra fields by default; models cheerfully add\n  `summary` or `confidence` to your `Plan` schema and `with_structured_output`\n  crashes with `ValidationError: extra fields not permitted`.\n\nThis skill walks through LCEL composition (`RunnableSequence`, `RunnableParallel`,\n`RunnableBranch`, `RunnablePassthrough`, `RunnableLambda`); the correct\n`exceptions_to_handle` whitelist per provider; `max_concurrency` tuning with\nsafe ceilings (10 for most providers, 20+ with a semaphore); and prompt\ntemplates that survive untrusted input. Pin: `langchain-core 1.0.x`,\n`langchain-anthropic 1.0.x`, `langchain-openai 1.0.x`. Pain-catalog anchors:\nP07, P08, P53, P57.\n\n## Prerequisites\n\n- Python 3.10+ (3.12+ fixes the `KeyboardInterrupt` half of P07 — upgrade if you can)\n- `langchain-core >= 1.0, \u003C 2.0`\n- At least one provider: `pip install langchain-anthropic langchain-openai`\n- `pydantic >= 2.0` for schema-aware composition\n- Completed `langchain-model-inference` — the chat-model factory from that skill is reused here\n\n## Instructions\n\n### Step 1 — Compose with typed runnables, not lambdas\n\n```python\nfrom langchain_anthropic import ChatAnthropic\nfrom langchain_core.prompts import ChatPromptTemplate\nfrom langchain_core.output_parsers import StrOutputParser\nfrom langchain_core.runnables import RunnableParallel, RunnablePassthrough\n\nllm = ChatAnthropic(model=\"claude-sonnet-4-6\", timeout=30, max_retries=2)\n\nprompt = ChatPromptTemplate.from_messages(\n    [(\"system\", \"You are a summarizer.\"), (\"human\", \"{text}\")],\n    template_format=\"jinja2\",  # P57 — see Step 4\n)\n\n# Sequence: prompt -> llm -> str\nchain = prompt | llm | StrOutputParser()\n\n# Parallel: run two sub-chains and merge\nenriched = RunnableParallel(\n    summary=chain,\n    original=RunnablePassthrough(),\n)\n```\n\nThe `|` operator creates a `RunnableSequence`. Each step has a declared input\nand output shape — swap a concrete model for a router and the type contract\nholds. See [Runnable Composition Matrix](references\u002Frunnable-composition-matrix.md)\nfor when to reach for `RunnableSequence` vs `RunnableParallel` vs `RunnableBranch`\nvs `RunnableLambda`, with input\u002Foutput shape conventions for each.\n\n### Step 2 — Add fallbacks with a narrow exception whitelist\n\n```python\nfrom anthropic import APIError, APITimeoutError, RateLimitError\nfrom langchain_openai import ChatOpenAI\n\nbackup = ChatOpenAI(model=\"gpt-4o\", timeout=30, max_retries=2)\nbackup_chain = prompt | backup | StrOutputParser()\n\n# GOOD — only retry on transient provider errors\nresilient = chain.with_fallbacks(\n    [backup_chain],\n    exceptions_to_handle=(RateLimitError, APIError, APITimeoutError),\n)\n\n# BAD — default `(Exception,)` catches KeyboardInterrupt on Python \u003C3.12 (P07)\n# resilient_bad = chain.with_fallbacks([backup_chain])\n```\n\nThe default `exceptions_to_handle=(Exception,)` on Python \u003C3.12 inherits\n`KeyboardInterrupt` and `SystemExit` into the caught set — which means a\n`Ctrl+C` during a long `.batch()` run falls through to the backup instead of\nstopping. Python 3.12+ moved these under `BaseException` directly, which fixes\nthe inheritance path, but the default is still too broad: a Pydantic\n`ValidationError` or a `ToolException` will trigger a pointless backup call.\nSee [Fallback Exception List](references\u002Ffallback-exception-list.md) for the\ncurated whitelist per provider with concrete imports.\n\n### Step 3 — Batch with explicit concurrency\n\n```python\nimport asyncio\n\ninputs = [{\"text\": doc} for doc in documents]\n\n# Synchronous batch — blocks until done\nresults = chain.batch(inputs, config={\"max_concurrency\": 10})\n\n# Async batch — non-blocking\nresults = await chain.abatch(inputs, config={\"max_concurrency\": 10})\n```\n\nSafe ceilings: **10** for Anthropic and OpenAI at default tier; **20+** only\nbehind an `asyncio.Semaphore` if you are also tracking rate-limit headers.\nClaude TPM\u002FRPM limits vary by tier; OpenAI's TPD (tokens per day) is the\nbinding limit at scale. See [Batch Concurrency Tuning](references\u002Fbatch-concurrency-tuning.md)\nfor per-provider ceilings and the semaphore pattern.\n\n`invoke` vs `batch` vs `stream` — when each is correct:\n\n| Method | Input shape | Concurrency | Error behavior | When to use |\n|---|---|---|---|---|\n| `.invoke(x)` | Single | 1 | Raises on failure | One-shot call, interactive, tests |\n| `.batch(xs, config={\"max_concurrency\": N})` | List | N parallel | Raises on first failure unless `return_exceptions=True` | Bulk sync workloads, ETL, eval harnesses |\n| `.abatch(xs, config={\"max_concurrency\": N})` | List | N parallel (async) | Same as `.batch` | Event loops, async web servers, LangGraph nodes |\n| `.stream(x)` | Single | 1, chunked | Raises on failure | Interactive UI, live token display |\n| `.astream(x)` \u002F `.astream_events(x, version=\"v2\")` | Single | 1, chunked (async) | Raises on failure | Async UIs, event-driven pipelines, token metering (see `langchain-model-inference`) |\n\nPass `return_exceptions=True` in the config to keep a batch from aborting on\nthe first failure — exceptions come back in the result list instead of raising.\n\n### Step 4 — Escape prompt templates for untrusted input\n\n```python\nfrom langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n\n# BAD — default f-string format crashes on literal `{` in user input (P57)\nbad = ChatPromptTemplate.from_messages(\n    [(\"system\", \"Reply in JSON\"), (\"human\", \"{user_text}\")]\n)\nbad.invoke({\"user_text\": '{\"error\": \"oops\"}'})  # KeyError: 'error'\n\n# GOOD — jinja2 treats `{...}` as literal, uses `{{ var }}` for substitution\ngood = ChatPromptTemplate.from_messages(\n    [(\"system\", \"Reply in JSON\"), (\"human\", \"{{ user_text }}\")],\n    template_format=\"jinja2\",\n)\ngood.invoke({\"user_text\": '{\"error\": \"oops\"}'})  # OK\n\n# MIXED — message history is a list, use MessagesPlaceholder\nwith_history = ChatPromptTemplate.from_messages([\n    (\"system\", \"You are a helpful assistant.\"),\n    MessagesPlaceholder(\"history\"),\n    (\"human\", \"{{ question }}\"),\n], template_format=\"jinja2\")\n```\n\nRule of thumb: if any variable can contain user-provided free text (a paste,\na transcript, a code block), use `template_format=\"jinja2\"`. The f-string\nformat is fine for trusted template authors composing fixed instructions, but\nit is the wrong tool for user input. See [Prompt Template Escaping](references\u002Fprompt-template-escaping.md)\nfor the full brace-escaping rules and a `MessagesPlaceholder` reference.\n\n### Step 5 — Validate structured output with `extra=\"ignore\"`\n\n```python\nfrom pydantic import BaseModel, ConfigDict, Field\n\nclass Plan(BaseModel):\n    # P53 — without this, the chain crashes when the model adds extra fields\n    model_config = ConfigDict(extra=\"ignore\")\n    steps: list[str] = Field(default_factory=list)\n    estimated_minutes: int\n\nstructured_chain = prompt | llm.with_structured_output(Plan, method=\"json_schema\")\n```\n\nPydantic v2 rejects unknown fields by default. Models trained on \"be helpful\"\nadd `summary`, `confidence`, `rationale` — the schema crashes instead of\ndropping them. `extra=\"ignore\"` is the right default for model outputs.\n\n## Output\n\n- `RunnableSequence` \u002F `RunnableParallel` composition with declared input\u002Foutput shapes\n- `.with_fallbacks(exceptions_to_handle=(...))` with a narrow, provider-specific whitelist\n- `.batch()` \u002F `.abatch()` with explicit `max_concurrency` (10 default, 20+ behind semaphore)\n- `ChatPromptTemplate.from_messages(..., template_format=\"jinja2\")` for any template touching user input\n- Pydantic schemas with `ConfigDict(extra=\"ignore\")` for structured output\n- A clear `invoke` \u002F `batch` \u002F `abatch` \u002F `stream` \u002F `astream` decision matrix for each chain stage\n\n## Error Handling\n\n| Error | Cause | Fix |\n|-------|-------|-----|\n| `Ctrl+C` does not stop a long `.batch()`; fallback keeps running | `exceptions_to_handle=(Exception,)` swallows `KeyboardInterrupt` on Python \u003C3.12 (P07) | Pass a narrow tuple: `exceptions_to_handle=(RateLimitError, APIError, APITimeoutError)` |\n| `.batch(inputs)` takes same time as sequential loop | `max_concurrency` defaults to 1 (P08) | `config={\"max_concurrency\": 10}`; raise to 20+ only with a semaphore |\n| `KeyError: '\u003Csome-token>'` when invoking a `ChatPromptTemplate` | f-string parser reads user input's `{` as a variable (P57) | `template_format=\"jinja2\"`; escape literals as `{{`\u002F`}}` in f-string mode |\n| `ValidationError: extra fields not permitted` on structured output | Pydantic v2 strict-by-default (P53) | `model_config = ConfigDict(extra=\"ignore\")` on the schema |\n| `ValidationError` caught by fallback and treated as transient | Fallback whitelist too broad | Remove `ValidationError` from `exceptions_to_handle` so it surfaces |\n| `.batch` aborts on the first failure, losing all results | Default raises on first error | Pass `config={\"max_concurrency\": 10, \"return_exceptions\": True}` and filter |\n| Fallback chain never fires even on genuine `RateLimitError` | Provider's own `max_retries` consumes the error first | Lower `max_retries=0` on the primary when a fallback chain is the retry strategy |\n\n## Examples\n\n### Fan-out enrichment with RunnableParallel\n\nA common pattern — given a document, produce a summary, extracted entities,\nand sentiment in parallel. `RunnableParallel` runs sub-chains concurrently and\nmerges results into a dict. Combined with `.batch()` at the outer level, you\nget N documents times 3 sub-chains in flight up to `max_concurrency`.\n\nSee [Runnable Composition Matrix](references\u002Frunnable-composition-matrix.md)\nfor the fan-out\u002Ffan-in pattern and the input\u002Foutput shape of each runnable type.\n\n### Resilient chain with per-provider fallback\n\nPrimary: Claude Sonnet 4.6. Fallback: GPT-4o. Catch only `RateLimitError`,\n`APIError`, and `APITimeoutError` from each SDK — let `AuthenticationError`\nand `ValidationError` crash the process so they get debugged, not masked.\n\nSee [Fallback Exception List](references\u002Ffallback-exception-list.md) for the\nconcrete imports per provider and a note on why `BadRequestError` should not\nbe in the whitelist.\n\n### High-throughput batch with semaphore-bounded concurrency\n\nAt N >= 20 concurrent in-flight calls, provider rate-limit headers become the\nbottleneck. Wrap `.abatch()` in an `asyncio.Semaphore` and honor the\n`retry-after` header on 429 responses.\n\nSee [Batch Concurrency Tuning](references\u002Fbatch-concurrency-tuning.md) for the\nsemaphore pattern and a table of provider TPM\u002FRPM limits per tier.\n\n### Prompt template over user-pasted JSON payload\n\nSupport ticket triage where users paste arbitrary JSON from their app's error\nlog. Without `template_format=\"jinja2\"`, every single ticket with a JSON body\ncrashes the chain at template-render time.\n\nSee [Prompt Template Escaping](references\u002Fprompt-template-escaping.md) for the\nworked example and the `MessagesPlaceholder` pattern for chat history.\n\n## Resources\n\n- [LangChain Python: Runnable interface](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fconcepts\u002Frunnables\u002F)\n- [LangChain Python: `with_fallbacks`](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fhow_to\u002Ffallbacks\u002F)\n- [LangChain Python: `batch` and `abatch`](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fhow_to\u002Fparallel\u002F)\n- [`ChatPromptTemplate` reference](https:\u002F\u002Fpython.langchain.com\u002Fapi_reference\u002Fcore\u002Fprompts\u002Flangchain_core.prompts.chat.ChatPromptTemplate.html)\n- [Pydantic v2 `ConfigDict`](https:\u002F\u002Fdocs.pydantic.dev\u002Flatest\u002Fapi\u002Fconfig\u002F)\n- [LangChain 1.0 release notes](https:\u002F\u002Fblog.langchain.com\u002Flangchain-langgraph-1dot0\u002F)\n- Pack pain catalog: `docs\u002Fpain-catalog.md` (entries P07, P08, P53, P57)\n",{"name":5,"tags":24,"author":32,"license":15,"version":33,"description":34,"allowed-tools":35,"compatible-with":36},[25,26,27,28,29,30,31],"saas","langchain","langgraph","python","langchain-1.0","lcel","runnables","Jeremy Longshore \u003Cjeremy@intentsolutions.io>","2.0.0","Compose LangChain 1.0 Python runnables with the production defaults the docs\ndo not warn about: parallel batching, narrow fallbacks, and brace-safe prompts.\nUse when building an LCEL chain with RunnableSequence \u002F RunnableParallel,\nadding resilience via `.with_fallbacks()`, tuning throughput with `.batch()`\nor `.abatch()`, or wrapping user input in a prompt template.\nTrigger with \"langchain runnable\", \"with_fallbacks\", \"langchain batch\",\n\"runnable sequence\", \"lcel\", \"runnableparallel\", \"chain composition\".\n","Read, Write, Edit, Bash(python:*), Bash(pip:*)","claude-code, codex","main","99825ad3f3bcc6597ddcc7294a14e6e922f2b67b","skills\u002Fsaas-packs--langchain-py-pack--langchain-sdk-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":47,"prompt":57,"zipAvailable":58},[48,51,54],{"tool":49,"command":50},"npx","npx skills add jukeyman\u002Fjukeyman-skills --skill langchain-sdk-patterns",{"tool":52,"command":53},"bunx","bunx skills add jukeyman\u002Fjukeyman-skills --skill langchain-sdk-patterns",{"tool":55,"command":56},"pnpm","pnpm dlx skills add jukeyman\u002Fjukeyman-skills --skill langchain-sdk-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--langchain-py-pack--langchain-sdk-patterns\u002FSKILL.md",true,[],[61,68,75,82,89,97],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"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":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"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":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"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":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"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":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":93,"sourceHtmlUrl":94,"categories":95,"keywords":96,"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":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"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",[],[]]