[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79296846EMG7FA3JC1WDE4A":3,"skill-same:01M79296846EMG7FA3JC1WDE4A":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},"01M79296846EMG7FA3JC1WDE4A","langchain-core-workflow",null,"Compose LangChain 1.0 chains with RunnableParallel, RunnableBranch,\nRunnablePassthrough.assign, and RunnableLambda — correct input\u002Foutput shapes,\ndebug probes, and typed composition that catches dict-shape bugs before\ninvocation. Use when wiring multi-step chains, parallel retrievals,\nconditional routing, or threading state through a chain for RAG,\nclassification, or extraction pipelines.\nTrigger with \"runnable parallel\", \"runnable branch\", \"langchain rag\ncomposition\", \"passthrough assign\", \"langchain lcel\", \"runnable lambda\",\n\"debug probe\".","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-core-workflow\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: langchain-core-workflow\ndescription: |\n  Compose LangChain 1.0 chains with RunnableParallel, RunnableBranch,\n  RunnablePassthrough.assign, and RunnableLambda — correct input\u002Foutput shapes,\n  debug probes, and typed composition that catches dict-shape bugs before\n  invocation. Use when wiring multi-step chains, parallel retrievals,\n  conditional routing, or threading state through a chain for RAG,\n  classification, or extraction pipelines.\n  Trigger with \"runnable parallel\", \"runnable branch\", \"langchain rag\n  composition\", \"passthrough assign\", \"langchain lcel\", \"runnable lambda\",\n  \"debug probe\".\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, lcel, runnables, rag]\ncompatible-with: claude-code, codex\n---\n\n# LangChain Core Workflow (Python)\n\n## Overview\n\nAn engineer wires a four-stage LCEL chain: classify the question, retrieve\ncontext, format the prompt, invoke the LLM. It looks clean:\n\n```python\nchain = (\n    RunnablePassthrough.assign(category=classifier)\n    | RunnablePassthrough.assign(docs=retriever)\n    | prompt\n    | llm\n    | StrOutputParser()\n)\n\nchain.invoke({\"question\": \"What's our refund policy?\"})\n```\n\nThe call returns this:\n\n```\nTraceback (most recent call last):\n  ...\n  File \"...\u002Frunnables\u002Fbase.py\", line 3421, in _call_with_config\n    output = call_func_with_variable_args(func, input, ...)\n  File \"...\u002Fprompts\u002Fchat.py\", line 1021, in _format_messages\n    return await ... await self.ainvoke({**kwargs})\nKeyError: 'question'\n```\n\nNothing in that stack says **which stage produced the wrong dict shape**. The\n`RunnablePassthrough.assign(docs=retriever)` call silently rebuilt the dict\nand — because `retriever` was itself a `Runnable[str, list[Document]]` that\ntook the `question` *string*, not the dict — a mis-piped intermediate value\noverwrote the `question` key. The prompt template expected `{question}` and\nblew up. This is P06 in the pack's pain catalog: `.pipe()` on mismatched dict\nshape raises `KeyError` deep in runnable internals with no hint at the\noffending stage.\n\nThe fix is **two patterns you install once and never remove**:\n\n1. **Debug probes** — a `RunnableLambda` that logs dict keys between every two\n   stages. \u003C1ms overhead per invocation. Surfaces the exact stage that mutates\n   the shape.\n2. **Typed composition** — annotate each chain with `RunnableSerializable[InputT, OutputT]`\n   plus pydantic `BaseModel` types so mypy flags the mismatch at lint time\n   instead of at `.invoke()`.\n\nMeanwhile, a second trap waits for anyone tempted to wrap tool-using chains\nin the legacy `AgentExecutor`: it silently swallows intermediate tool errors\nas empty-string observations and the agent cheerfully answers \"I couldn't\nfind the answer\" (P09). For agent loops in LangChain 1.0, skip `AgentExecutor`\nand use LangGraph's `create_react_agent` — errors raise, not vanish. This\nskill cross-references `langchain-langgraph-agents` (L26) for that path.\n\nComposition primitives covered — with input\u002Foutput shapes and use cases — are\n`RunnableParallel` (fan-out, 2–3× wall-clock win on 2 independent retrievals),\n`RunnableBranch` (conditional routing with mandatory default), `RunnablePassthrough.assign`\n(merge computed fields without losing input), and `RunnableLambda` (arbitrary\nPython, used here for debug probes and shape assertions). Pin: `langchain-core 1.0.x`.\nPain-catalog anchors: P06, P09.\n\n## Prerequisites\n\n- Python 3.10+\n- `langchain-core >= 1.0, \u003C 2.0`\n- `pydantic >= 2.0` for typed composition\n- At least one chat provider installed (see `langchain-model-inference`)\n- Familiarity with the composition primitives introduced in `langchain-sdk-patterns`\n\n## Instructions\n\n### Step 1 — Fan-out with `RunnableParallel` for independent sub-tasks\n\n`RunnableParallel({\"a\": chain_a, \"b\": chain_b})` forwards the same input to\nboth branches and runs them concurrently, merging results into a dict.\nWall-clock collapses to the slower branch — 2–3× speedup on two parallel\nretrievals is typical (dense vector search + BM25, or tool-use + analysis).\n\n```python\nfrom langchain_core.runnables import RunnableParallel, RunnablePassthrough\n\n# Hybrid retrieval: dense vector search and BM25 at the same time\nhybrid = RunnableParallel(\n    dense=dense_retriever,     # Runnable[str, list[Document]]\n    bm25=bm25_retriever,       # Runnable[str, list[Document]]\n    query=RunnablePassthrough() # keep the original string for downstream stages\n)\n\n# Output: {\"dense\": [...], \"bm25\": [...], \"query\": \"...\"}\nresult = hybrid.invoke(\"refund policy for damaged goods\")\n```\n\nInput shape: whatever the sub-chains accept (all must accept the same shape).\nOutput shape: `dict` with one key per sub-chain. If one branch takes 5× longer,\nyour total latency is that branch — not the sum. See\n[Parallel vs Sequential](references\u002Fparallel-vs-sequential.md) for the async\n`.abatch()` variant, shared-state gotchas, and a benchmarking template.\n\n### Step 2 — Route on input with `RunnableBranch`\n\n`RunnableBranch((cond, runnable), ..., default)` dispatches per-input to the\nfirst matching branch. **The default is mandatory** — without one you get a\nsilent fallthrough on unmatched inputs.\n\n```python\nfrom langchain_core.runnables import RunnableBranch\n\nrouter = RunnableBranch(\n    (lambda x: x[\"category\"] == \"refund\", refund_chain),\n    (lambda x: x[\"category\"] == \"shipping\", shipping_chain),\n    (lambda x: len(x[\"question\"]) > 2000, long_form_chain),\n    general_chain,  # default — required\n)\n```\n\nClassifier-gated routes are the common case: a cheap small-model classifier\nruns first, its label goes into the dict via `RunnablePassthrough.assign`, and\n`RunnableBranch` dispatches. See [Branch Routing Patterns](references\u002Fbranch-routing-patterns.md)\nfor the signature, classifier-gated route recipe, fallback route pattern, and\npytest patterns for each branch in isolation.\n\n### Step 3 — Thread state with `RunnablePassthrough.assign`\n\n`.assign(field=...)` merges a computed field into the input dict without\nlosing any existing keys. This is the primary pattern for staged context\nassembly in RAG:\n\n```python\nfrom langchain_core.runnables import RunnablePassthrough\n\ndef format_docs(docs: list) -> str:\n    return \"\\n\\n\".join(d.page_content for d in docs)\n\n# At each step, the dict grows: {question} -> {question, docs} -> {question, docs, context}\nstaged = (\n    RunnablePassthrough.assign(docs=retriever)         # adds \"docs\"\n    | RunnablePassthrough.assign(context=lambda x: format_docs(x[\"docs\"]))  # adds \"context\"\n)\n\nstaged.invoke({\"question\": \"...\"})\n# {\"question\": \"...\", \"docs\": [...], \"context\": \"...\"}\n```\n\nThe input dict passes through unchanged; the new field is the only mutation.\nThis is the safest shape-preserving primitive in LCEL — use it whenever a\ndownstream stage needs both the original input and a computed value. See\n[Passthrough Assign Patterns](references\u002Fpassthrough-assign-patterns.md) for\nstaged context assembly, the `itemgetter` variant for pulling a single field\ninto a typed chain, and anti-patterns that re-shadow input keys.\n\n### Step 4 — Use `RunnableLambda` for debug probes (and little else)\n\n`RunnableLambda(fn)` wraps any Python callable into a runnable. Its best use\nis **debug probes** — log intermediate values without breaking the pipe:\n\n```python\nfrom langchain_core.runnables import RunnableLambda\n\ndef probe(stage: str):\n    \"\"\"\u003C1ms overhead per invocation. Returns input unchanged.\"\"\"\n    def _probe(x):\n        keys = list(x.keys()) if isinstance(x, dict) else type(x).__name__\n        print(f\"[probe:{stage}] keys={keys}\")\n        return x\n    return RunnableLambda(_probe)\n\nchain = (\n    probe(\"input\")\n    | RunnablePassthrough.assign(category=classifier)\n    | probe(\"after-classify\")\n    | RunnablePassthrough.assign(docs=retriever)\n    | probe(\"after-retrieve\")\n    | prompt\n    | probe(\"after-prompt\")\n    | llm\n    | StrOutputParser()\n)\n```\n\nWhen P06's `KeyError` strikes, the last probe that printed tells you exactly\nwhich stage produced the wrong shape. Remove the probes (or gate them on an\nenv var) after debugging. For production chains that stay observable, prefer\n`langchain.debug = True` or LangSmith tracing over `print` probes.\n\nSee [Debug Probes](references\u002Fdebug-probes.md) for a shape-assertion decorator,\nthe `langchain.debug` flag, verbose mode, and a probe that raises instead of\nprints (useful in CI).\n\nAvoid `RunnableLambda` for real logic — it loses LangSmith tracing fidelity\n(input\u002Foutput become opaque blobs) and a >3-line lambda is a sign you want a\nconcrete `Runnable` subclass. See the anti-pattern note in\n`langchain-sdk-patterns\u002Freferences\u002Frunnable-composition-matrix.md`.\n\n### Step 5 — Type chains with `RunnableSerializable[InputT, OutputT]`\n\nThe root fix for P06 is static typing at chain boundaries. `RunnableSerializable`\ncarries input and output type parameters; pair it with pydantic `BaseModel`s\nand mypy catches dict-shape mismatches at lint time:\n\n```python\nfrom pydantic import BaseModel\nfrom langchain_core.runnables import RunnableSerializable\n\nclass RAGInput(BaseModel):\n    question: str\n    user_id: str\n\nclass RAGOutput(BaseModel):\n    answer: str\n    citations: list[str]\n\ndef build_rag_chain() -> RunnableSerializable[RAGInput, RAGOutput]:\n    return (\n        RunnablePassthrough.assign(docs=retriever)\n        | RunnablePassthrough.assign(context=lambda x: format_docs(x[\"docs\"]))\n        | prompt\n        | llm.with_structured_output(RAGOutput)\n    )\n\nrag: RunnableSerializable[RAGInput, RAGOutput] = build_rag_chain()\n```\n\nCall `rag.input_schema.model_json_schema()` to dump the runtime-enforced\nschema for tests or assertions. Combined with the debug probes from Step 4,\nthis is the typed-composition pattern that retires P06 in new code.\n\n### Step 6 — RAG composition example (end-to-end)\n\n```python\nfrom langchain_core.prompts import ChatPromptTemplate\nfrom langchain_core.output_parsers import StrOutputParser\nfrom langchain_core.runnables import RunnablePassthrough, RunnableParallel\n\nprompt = ChatPromptTemplate.from_messages([\n    (\"system\", \"Answer from the context. If not in context, say so.\"),\n    (\"human\", \"Context:\\n{{ context }}\\n\\nQuestion: {{ question }}\"),\n], template_format=\"jinja2\")\n\n# Hybrid retrieval (parallel) + staged context assembly\nrag_chain = (\n    RunnableParallel(\n        dense=dense_retriever,\n        bm25=bm25_retriever,\n        question=RunnablePassthrough(),\n    )\n    | RunnablePassthrough.assign(\n        context=lambda x: format_hybrid(x[\"dense\"], x[\"bm25\"])\n    )\n    | prompt\n    | llm\n    | StrOutputParser()\n)\n\nanswer = rag_chain.invoke(\"What's the return window for electronics?\")\n```\n\nThis is the reference composition — parallel dual-retrieval (2–3× speedup vs\nsequential), staged context assembly via `.assign`, jinja2 prompt templating\n(escapes literal `{` from retrieved docs, see `langchain-sdk-patterns`), and\na simple string output. Add debug probes from Step 4 during development.\n\n### Step 7 — For agent loops, skip `AgentExecutor`\n\nLegacy `AgentExecutor` silently catches tool exceptions and feeds the error\nmessage back as an empty-string observation — the agent then answers \"I\ncouldn't find the answer\" with no trace of the underlying failure (P09). In\nLangChain 1.0, use LangGraph's `create_react_agent` instead: tool errors\nraise by default, intermediate steps are inspectable, and recursion limits\nare explicit.\n\nSee the pack's `langchain-langgraph-agents` skill (L26) for the agent\nmigration path. The composition primitives in this skill (`RunnableParallel`,\n`RunnableBranch`, `.assign`) remain the right tools for the non-agent parts\nof any LangGraph workflow — they compose inside a LangGraph node.\n\n## Composition Pattern Table\n\n| Pattern | Input shape | Output shape | Typical use |\n|---|---|---|---|\n| `a \\| b \\| c` (RunnableSequence) | `a.input` | `c.output` | Linear pipeline: prompt → llm → parser |\n| `RunnableParallel(x=ch1, y=ch2)` | forwarded to both | `{\"x\": ch1.output, \"y\": ch2.output}` | Fan-out: hybrid retrieval, tool-use + analysis |\n| `RunnableBranch((cond, ch), ..., default)` | anything cond accepts | `ch.output` or `default.output` | Classifier-gated routing, per-input dispatch |\n| `RunnablePassthrough()` | any | same as input | Keep original value alongside a transform in a parallel |\n| `RunnablePassthrough.assign(k=ch)` | `dict` | input dict with `\"k\"` added (ch.output) | Staged context assembly, threading state |\n| `RunnableLambda(fn)` | `fn`'s arg | `fn`'s return | Debug probes, shape assertions — avoid for real logic |\n\n## Output\n\n- Multi-step chains composed from `RunnableParallel`, `RunnableBranch`, `RunnablePassthrough.assign`, and `RunnableLambda` with declared input\u002Foutput shapes\n- Debug-probe pattern (\u003C1ms per invocation) that surfaces the exact stage producing a wrong dict shape when P06 strikes\n- Typed-composition pattern (`RunnableSerializable[InputT, OutputT]` + pydantic `BaseModel`) that catches P06 at lint time before invocation\n- RAG composition recipe: hybrid parallel retrieval + staged context assembly + prompt + llm + parser, 2–3× wall-clock win on dual retrieval\n- Cross-reference to `langchain-langgraph-agents` (L26) for agent loops that avoid P09's silent-error trap\n\n## Error Handling\n\n| Error | Cause | Fix |\n|-------|-------|-----|\n| `KeyError: 'question'` deep in runnable internals, no stage named in stack | `RunnablePassthrough.assign` or an upstream runnable rebuilt the dict in a way a downstream stage does not expect (P06) | Insert `RunnableLambda` debug probes between stages; annotate with `RunnableSerializable[InputT, OutputT]` + pydantic for lint-time catch |\n| Agent returns \"I couldn't find the answer\" with no error in logs | Legacy `AgentExecutor` swallows tool exceptions as empty-string observations (P09) | Migrate to LangGraph `create_react_agent`; see `langchain-langgraph-agents` (L26) |\n| `RunnableBranch` returns wrong branch's output for unmatched input | No default branch supplied; LCEL fell through to the last-declared pair | Always pass a default as the final positional arg to `RunnableBranch((cond, ch), ..., default_ch)` |\n| `.assign` computed field shadows input key | `RunnablePassthrough.assign(question=...)` overwrote the original `question` | Name computed fields distinctly from input keys; use `itemgetter` to extract when you need the original |\n| `RunnableLambda` call shows as opaque blob in LangSmith | Lambda's input\u002Foutput are not traced at block-level | Replace with a concrete `Runnable` subclass or use `.assign(key=...)` with a named function |\n| `RunnableParallel` branches race on shared mutable state | A lambda closed over a non-thread-safe object | Keep parallel branches side-effect-free; materialize shared state before the parallel block |\n\n## Examples\n\n### Hybrid retrieval with parallel branches\n\nTwo retrievers run concurrently on the same query — dense vector search via\nan embedding model and BM25 via rank-bm25. `RunnableParallel` merges the\nresults; a downstream `.assign` step formats the union. Wall-clock is the\nslower retriever, not the sum — typically a 2–3× win over sequential dense\nthen BM25.\n\nSee [Parallel vs Sequential](references\u002Fparallel-vs-sequential.md) for the\nbenchmarking template and async variant.\n\n### Classifier-gated routing for a customer support chain\n\nA cheap small-model classifier runs first and tags the input dict with a\n`category`. `RunnableBranch` dispatches refunds, shipping, and general\nquestions to specialist chains. The default branch handles unmatched inputs\nwith a disclaimer prompt.\n\nSee [Branch Routing Patterns](references\u002Fbranch-routing-patterns.md) for the\nclassifier-gated recipe and pytest isolation patterns.\n\n### Staged context assembly for RAG with citations\n\n`RunnablePassthrough.assign(docs=retriever)` then\n`.assign(context=format_docs)` builds the prompt context without dropping the\noriginal `question`. A final `.assign(citations=lambda x: [d.metadata[\"url\"] for d in x[\"docs\"]])`\nthreads citations through to the structured output.\n\nSee [Passthrough Assign Patterns](references\u002Fpassthrough-assign-patterns.md)\nfor the staged pattern and the anti-pattern around key shadowing.\n\n### Debug probe that raises in CI\n\nIn development, probes `print`. In CI, they assert on expected keys and raise\non mismatch — catching P06 during test runs instead of at production invoke.\n\nSee [Debug Probes](references\u002Fdebug-probes.md) for the shape-assertion\ndecorator and the `langchain.debug` flag.\n\n## Resources\n\n- [LangChain Python: Runnable interface](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fconcepts\u002Frunnables\u002F)\n- [LangChain Python: RunnableParallel](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fhow_to\u002Fparallel\u002F)\n- [LangChain Python: RunnableBranch](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fhow_to\u002Frouting\u002F)\n- [LangChain Python: RunnablePassthrough](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fhow_to\u002Fpassthrough\u002F)\n- [LangChain Python: debug mode](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fhow_to\u002Fdebugging\u002F)\n- [LangChain 1.0 release notes](https:\u002F\u002Fblog.langchain.com\u002Flangchain-langgraph-1dot0\u002F)\n- Pair skill: `langchain-sdk-patterns` (composition primitives, fallbacks, concurrency)\n- Agent alternative: `langchain-langgraph-agents` (L26) — avoids P09\n- Pack pain catalog: `docs\u002Fpain-catalog.md` (entries P06, P09)\n","# LangChain Core Workflow (Python)\n\n## Overview\n\nAn engineer wires a four-stage LCEL chain: classify the question, retrieve\ncontext, format the prompt, invoke the LLM. It looks clean:\n\n```python\nchain = (\n    RunnablePassthrough.assign(category=classifier)\n    | RunnablePassthrough.assign(docs=retriever)\n    | prompt\n    | llm\n    | StrOutputParser()\n)\n\nchain.invoke({\"question\": \"What's our refund policy?\"})\n```\n\nThe call returns this:\n\n```\nTraceback (most recent call last):\n  ...\n  File \"...\u002Frunnables\u002Fbase.py\", line 3421, in _call_with_config\n    output = call_func_with_variable_args(func, input, ...)\n  File \"...\u002Fprompts\u002Fchat.py\", line 1021, in _format_messages\n    return await ... await self.ainvoke({**kwargs})\nKeyError: 'question'\n```\n\nNothing in that stack says **which stage produced the wrong dict shape**. The\n`RunnablePassthrough.assign(docs=retriever)` call silently rebuilt the dict\nand — because `retriever` was itself a `Runnable[str, list[Document]]` that\ntook the `question` *string*, not the dict — a mis-piped intermediate value\noverwrote the `question` key. The prompt template expected `{question}` and\nblew up. This is P06 in the pack's pain catalog: `.pipe()` on mismatched dict\nshape raises `KeyError` deep in runnable internals with no hint at the\noffending stage.\n\nThe fix is **two patterns you install once and never remove**:\n\n1. **Debug probes** — a `RunnableLambda` that logs dict keys between every two\n   stages. \u003C1ms overhead per invocation. Surfaces the exact stage that mutates\n   the shape.\n2. **Typed composition** — annotate each chain with `RunnableSerializable[InputT, OutputT]`\n   plus pydantic `BaseModel` types so mypy flags the mismatch at lint time\n   instead of at `.invoke()`.\n\nMeanwhile, a second trap waits for anyone tempted to wrap tool-using chains\nin the legacy `AgentExecutor`: it silently swallows intermediate tool errors\nas empty-string observations and the agent cheerfully answers \"I couldn't\nfind the answer\" (P09). For agent loops in LangChain 1.0, skip `AgentExecutor`\nand use LangGraph's `create_react_agent` — errors raise, not vanish. This\nskill cross-references `langchain-langgraph-agents` (L26) for that path.\n\nComposition primitives covered — with input\u002Foutput shapes and use cases — are\n`RunnableParallel` (fan-out, 2–3× wall-clock win on 2 independent retrievals),\n`RunnableBranch` (conditional routing with mandatory default), `RunnablePassthrough.assign`\n(merge computed fields without losing input), and `RunnableLambda` (arbitrary\nPython, used here for debug probes and shape assertions). Pin: `langchain-core 1.0.x`.\nPain-catalog anchors: P06, P09.\n\n## Prerequisites\n\n- Python 3.10+\n- `langchain-core >= 1.0, \u003C 2.0`\n- `pydantic >= 2.0` for typed composition\n- At least one chat provider installed (see `langchain-model-inference`)\n- Familiarity with the composition primitives introduced in `langchain-sdk-patterns`\n\n## Instructions\n\n### Step 1 — Fan-out with `RunnableParallel` for independent sub-tasks\n\n`RunnableParallel({\"a\": chain_a, \"b\": chain_b})` forwards the same input to\nboth branches and runs them concurrently, merging results into a dict.\nWall-clock collapses to the slower branch — 2–3× speedup on two parallel\nretrievals is typical (dense vector search + BM25, or tool-use + analysis).\n\n```python\nfrom langchain_core.runnables import RunnableParallel, RunnablePassthrough\n\n# Hybrid retrieval: dense vector search and BM25 at the same time\nhybrid = RunnableParallel(\n    dense=dense_retriever,     # Runnable[str, list[Document]]\n    bm25=bm25_retriever,       # Runnable[str, list[Document]]\n    query=RunnablePassthrough() # keep the original string for downstream stages\n)\n\n# Output: {\"dense\": [...], \"bm25\": [...], \"query\": \"...\"}\nresult = hybrid.invoke(\"refund policy for damaged goods\")\n```\n\nInput shape: whatever the sub-chains accept (all must accept the same shape).\nOutput shape: `dict` with one key per sub-chain. If one branch takes 5× longer,\nyour total latency is that branch — not the sum. See\n[Parallel vs Sequential](references\u002Fparallel-vs-sequential.md) for the async\n`.abatch()` variant, shared-state gotchas, and a benchmarking template.\n\n### Step 2 — Route on input with `RunnableBranch`\n\n`RunnableBranch((cond, runnable), ..., default)` dispatches per-input to the\nfirst matching branch. **The default is mandatory** — without one you get a\nsilent fallthrough on unmatched inputs.\n\n```python\nfrom langchain_core.runnables import RunnableBranch\n\nrouter = RunnableBranch(\n    (lambda x: x[\"category\"] == \"refund\", refund_chain),\n    (lambda x: x[\"category\"] == \"shipping\", shipping_chain),\n    (lambda x: len(x[\"question\"]) > 2000, long_form_chain),\n    general_chain,  # default — required\n)\n```\n\nClassifier-gated routes are the common case: a cheap small-model classifier\nruns first, its label goes into the dict via `RunnablePassthrough.assign`, and\n`RunnableBranch` dispatches. See [Branch Routing Patterns](references\u002Fbranch-routing-patterns.md)\nfor the signature, classifier-gated route recipe, fallback route pattern, and\npytest patterns for each branch in isolation.\n\n### Step 3 — Thread state with `RunnablePassthrough.assign`\n\n`.assign(field=...)` merges a computed field into the input dict without\nlosing any existing keys. This is the primary pattern for staged context\nassembly in RAG:\n\n```python\nfrom langchain_core.runnables import RunnablePassthrough\n\ndef format_docs(docs: list) -> str:\n    return \"\\n\\n\".join(d.page_content for d in docs)\n\n# At each step, the dict grows: {question} -> {question, docs} -> {question, docs, context}\nstaged = (\n    RunnablePassthrough.assign(docs=retriever)         # adds \"docs\"\n    | RunnablePassthrough.assign(context=lambda x: format_docs(x[\"docs\"]))  # adds \"context\"\n)\n\nstaged.invoke({\"question\": \"...\"})\n# {\"question\": \"...\", \"docs\": [...], \"context\": \"...\"}\n```\n\nThe input dict passes through unchanged; the new field is the only mutation.\nThis is the safest shape-preserving primitive in LCEL — use it whenever a\ndownstream stage needs both the original input and a computed value. See\n[Passthrough Assign Patterns](references\u002Fpassthrough-assign-patterns.md) for\nstaged context assembly, the `itemgetter` variant for pulling a single field\ninto a typed chain, and anti-patterns that re-shadow input keys.\n\n### Step 4 — Use `RunnableLambda` for debug probes (and little else)\n\n`RunnableLambda(fn)` wraps any Python callable into a runnable. Its best use\nis **debug probes** — log intermediate values without breaking the pipe:\n\n```python\nfrom langchain_core.runnables import RunnableLambda\n\ndef probe(stage: str):\n    \"\"\"\u003C1ms overhead per invocation. Returns input unchanged.\"\"\"\n    def _probe(x):\n        keys = list(x.keys()) if isinstance(x, dict) else type(x).__name__\n        print(f\"[probe:{stage}] keys={keys}\")\n        return x\n    return RunnableLambda(_probe)\n\nchain = (\n    probe(\"input\")\n    | RunnablePassthrough.assign(category=classifier)\n    | probe(\"after-classify\")\n    | RunnablePassthrough.assign(docs=retriever)\n    | probe(\"after-retrieve\")\n    | prompt\n    | probe(\"after-prompt\")\n    | llm\n    | StrOutputParser()\n)\n```\n\nWhen P06's `KeyError` strikes, the last probe that printed tells you exactly\nwhich stage produced the wrong shape. Remove the probes (or gate them on an\nenv var) after debugging. For production chains that stay observable, prefer\n`langchain.debug = True` or LangSmith tracing over `print` probes.\n\nSee [Debug Probes](references\u002Fdebug-probes.md) for a shape-assertion decorator,\nthe `langchain.debug` flag, verbose mode, and a probe that raises instead of\nprints (useful in CI).\n\nAvoid `RunnableLambda` for real logic — it loses LangSmith tracing fidelity\n(input\u002Foutput become opaque blobs) and a >3-line lambda is a sign you want a\nconcrete `Runnable` subclass. See the anti-pattern note in\n`langchain-sdk-patterns\u002Freferences\u002Frunnable-composition-matrix.md`.\n\n### Step 5 — Type chains with `RunnableSerializable[InputT, OutputT]`\n\nThe root fix for P06 is static typing at chain boundaries. `RunnableSerializable`\ncarries input and output type parameters; pair it with pydantic `BaseModel`s\nand mypy catches dict-shape mismatches at lint time:\n\n```python\nfrom pydantic import BaseModel\nfrom langchain_core.runnables import RunnableSerializable\n\nclass RAGInput(BaseModel):\n    question: str\n    user_id: str\n\nclass RAGOutput(BaseModel):\n    answer: str\n    citations: list[str]\n\ndef build_rag_chain() -> RunnableSerializable[RAGInput, RAGOutput]:\n    return (\n        RunnablePassthrough.assign(docs=retriever)\n        | RunnablePassthrough.assign(context=lambda x: format_docs(x[\"docs\"]))\n        | prompt\n        | llm.with_structured_output(RAGOutput)\n    )\n\nrag: RunnableSerializable[RAGInput, RAGOutput] = build_rag_chain()\n```\n\nCall `rag.input_schema.model_json_schema()` to dump the runtime-enforced\nschema for tests or assertions. Combined with the debug probes from Step 4,\nthis is the typed-composition pattern that retires P06 in new code.\n\n### Step 6 — RAG composition example (end-to-end)\n\n```python\nfrom langchain_core.prompts import ChatPromptTemplate\nfrom langchain_core.output_parsers import StrOutputParser\nfrom langchain_core.runnables import RunnablePassthrough, RunnableParallel\n\nprompt = ChatPromptTemplate.from_messages([\n    (\"system\", \"Answer from the context. If not in context, say so.\"),\n    (\"human\", \"Context:\\n{{ context }}\\n\\nQuestion: {{ question }}\"),\n], template_format=\"jinja2\")\n\n# Hybrid retrieval (parallel) + staged context assembly\nrag_chain = (\n    RunnableParallel(\n        dense=dense_retriever,\n        bm25=bm25_retriever,\n        question=RunnablePassthrough(),\n    )\n    | RunnablePassthrough.assign(\n        context=lambda x: format_hybrid(x[\"dense\"], x[\"bm25\"])\n    )\n    | prompt\n    | llm\n    | StrOutputParser()\n)\n\nanswer = rag_chain.invoke(\"What's the return window for electronics?\")\n```\n\nThis is the reference composition — parallel dual-retrieval (2–3× speedup vs\nsequential), staged context assembly via `.assign`, jinja2 prompt templating\n(escapes literal `{` from retrieved docs, see `langchain-sdk-patterns`), and\na simple string output. Add debug probes from Step 4 during development.\n\n### Step 7 — For agent loops, skip `AgentExecutor`\n\nLegacy `AgentExecutor` silently catches tool exceptions and feeds the error\nmessage back as an empty-string observation — the agent then answers \"I\ncouldn't find the answer\" with no trace of the underlying failure (P09). In\nLangChain 1.0, use LangGraph's `create_react_agent` instead: tool errors\nraise by default, intermediate steps are inspectable, and recursion limits\nare explicit.\n\nSee the pack's `langchain-langgraph-agents` skill (L26) for the agent\nmigration path. The composition primitives in this skill (`RunnableParallel`,\n`RunnableBranch`, `.assign`) remain the right tools for the non-agent parts\nof any LangGraph workflow — they compose inside a LangGraph node.\n\n## Composition Pattern Table\n\n| Pattern | Input shape | Output shape | Typical use |\n|---|---|---|---|\n| `a \\| b \\| c` (RunnableSequence) | `a.input` | `c.output` | Linear pipeline: prompt → llm → parser |\n| `RunnableParallel(x=ch1, y=ch2)` | forwarded to both | `{\"x\": ch1.output, \"y\": ch2.output}` | Fan-out: hybrid retrieval, tool-use + analysis |\n| `RunnableBranch((cond, ch), ..., default)` | anything cond accepts | `ch.output` or `default.output` | Classifier-gated routing, per-input dispatch |\n| `RunnablePassthrough()` | any | same as input | Keep original value alongside a transform in a parallel |\n| `RunnablePassthrough.assign(k=ch)` | `dict` | input dict with `\"k\"` added (ch.output) | Staged context assembly, threading state |\n| `RunnableLambda(fn)` | `fn`'s arg | `fn`'s return | Debug probes, shape assertions — avoid for real logic |\n\n## Output\n\n- Multi-step chains composed from `RunnableParallel`, `RunnableBranch`, `RunnablePassthrough.assign`, and `RunnableLambda` with declared input\u002Foutput shapes\n- Debug-probe pattern (\u003C1ms per invocation) that surfaces the exact stage producing a wrong dict shape when P06 strikes\n- Typed-composition pattern (`RunnableSerializable[InputT, OutputT]` + pydantic `BaseModel`) that catches P06 at lint time before invocation\n- RAG composition recipe: hybrid parallel retrieval + staged context assembly + prompt + llm + parser, 2–3× wall-clock win on dual retrieval\n- Cross-reference to `langchain-langgraph-agents` (L26) for agent loops that avoid P09's silent-error trap\n\n## Error Handling\n\n| Error | Cause | Fix |\n|-------|-------|-----|\n| `KeyError: 'question'` deep in runnable internals, no stage named in stack | `RunnablePassthrough.assign` or an upstream runnable rebuilt the dict in a way a downstream stage does not expect (P06) | Insert `RunnableLambda` debug probes between stages; annotate with `RunnableSerializable[InputT, OutputT]` + pydantic for lint-time catch |\n| Agent returns \"I couldn't find the answer\" with no error in logs | Legacy `AgentExecutor` swallows tool exceptions as empty-string observations (P09) | Migrate to LangGraph `create_react_agent`; see `langchain-langgraph-agents` (L26) |\n| `RunnableBranch` returns wrong branch's output for unmatched input | No default branch supplied; LCEL fell through to the last-declared pair | Always pass a default as the final positional arg to `RunnableBranch((cond, ch), ..., default_ch)` |\n| `.assign` computed field shadows input key | `RunnablePassthrough.assign(question=...)` overwrote the original `question` | Name computed fields distinctly from input keys; use `itemgetter` to extract when you need the original |\n| `RunnableLambda` call shows as opaque blob in LangSmith | Lambda's input\u002Foutput are not traced at block-level | Replace with a concrete `Runnable` subclass or use `.assign(key=...)` with a named function |\n| `RunnableParallel` branches race on shared mutable state | A lambda closed over a non-thread-safe object | Keep parallel branches side-effect-free; materialize shared state before the parallel block |\n\n## Examples\n\n### Hybrid retrieval with parallel branches\n\nTwo retrievers run concurrently on the same query — dense vector search via\nan embedding model and BM25 via rank-bm25. `RunnableParallel` merges the\nresults; a downstream `.assign` step formats the union. Wall-clock is the\nslower retriever, not the sum — typically a 2–3× win over sequential dense\nthen BM25.\n\nSee [Parallel vs Sequential](references\u002Fparallel-vs-sequential.md) for the\nbenchmarking template and async variant.\n\n### Classifier-gated routing for a customer support chain\n\nA cheap small-model classifier runs first and tags the input dict with a\n`category`. `RunnableBranch` dispatches refunds, shipping, and general\nquestions to specialist chains. The default branch handles unmatched inputs\nwith a disclaimer prompt.\n\nSee [Branch Routing Patterns](references\u002Fbranch-routing-patterns.md) for the\nclassifier-gated recipe and pytest isolation patterns.\n\n### Staged context assembly for RAG with citations\n\n`RunnablePassthrough.assign(docs=retriever)` then\n`.assign(context=format_docs)` builds the prompt context without dropping the\noriginal `question`. A final `.assign(citations=lambda x: [d.metadata[\"url\"] for d in x[\"docs\"]])`\nthreads citations through to the structured output.\n\nSee [Passthrough Assign Patterns](references\u002Fpassthrough-assign-patterns.md)\nfor the staged pattern and the anti-pattern around key shadowing.\n\n### Debug probe that raises in CI\n\nIn development, probes `print`. In CI, they assert on expected keys and raise\non mismatch — catching P06 during test runs instead of at production invoke.\n\nSee [Debug Probes](references\u002Fdebug-probes.md) for the shape-assertion\ndecorator and the `langchain.debug` flag.\n\n## Resources\n\n- [LangChain Python: Runnable interface](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fconcepts\u002Frunnables\u002F)\n- [LangChain Python: RunnableParallel](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fhow_to\u002Fparallel\u002F)\n- [LangChain Python: RunnableBranch](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fhow_to\u002Frouting\u002F)\n- [LangChain Python: RunnablePassthrough](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fhow_to\u002Fpassthrough\u002F)\n- [LangChain Python: debug mode](https:\u002F\u002Fpython.langchain.com\u002Fdocs\u002Fhow_to\u002Fdebugging\u002F)\n- [LangChain 1.0 release notes](https:\u002F\u002Fblog.langchain.com\u002Flangchain-langgraph-1dot0\u002F)\n- Pair skill: `langchain-sdk-patterns` (composition primitives, fallbacks, concurrency)\n- Agent alternative: `langchain-langgraph-agents` (L26) — avoids P09\n- Pack pain catalog: `docs\u002Fpain-catalog.md` (entries P06, P09)\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","lcel","runnables","rag","Jeremy Longshore \u003Cjeremy@intentsolutions.io>","2.0.0","Compose LangChain 1.0 chains with RunnableParallel, RunnableBranch,\nRunnablePassthrough.assign, and RunnableLambda — correct input\u002Foutput shapes,\ndebug probes, and typed composition that catches dict-shape bugs before\ninvocation. Use when wiring multi-step chains, parallel retrievals,\nconditional routing, or threading state through a chain for RAG,\nclassification, or extraction pipelines.\nTrigger with \"runnable parallel\", \"runnable branch\", \"langchain rag\ncomposition\", \"passthrough assign\", \"langchain lcel\", \"runnable lambda\",\n\"debug probe\".\n","Read, Write, Edit, Bash(python:*)","claude-code, codex","main","99825ad3f3bcc6597ddcc7294a14e6e922f2b67b","skills\u002Fsaas-packs--langchain-py-pack--langchain-core-workflow",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-core-workflow",{"tool":53,"command":54},"bunx","bunx skills add jukeyman\u002Fjukeyman-skills --skill langchain-core-workflow",{"tool":56,"command":57},"pnpm","pnpm dlx skills add jukeyman\u002Fjukeyman-skills --skill langchain-core-workflow","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--langchain-py-pack--langchain-core-workflow\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",[],[]]