LCEL & ChainsLesson 8

RunnableLambda

Simple Sequential Chains pipes pick_chain straight into explain_prompt. The model may return " <A> " or "<a>" instead of a clean tag.RunnableLambda(normalize_tag) sits between the two model steps — plain Python that returns {"tag": "a"} for explain_prompt.

Wrap a function

Pass a function to RunnableLambda(...) and pipe it with | — same syntax as prompts and models.

pick_chain → normalize_tag → explain:

input

{ feature: "links" }

step 1

pick_chain

lambda

normalize_tag

step 2

explain

output

explanation

normalize_tag turns "<a>" into {"tag": "a"} for the next prompt.
RunnableLambda(normalize_tag) pipes like a prompt or model.

Why normalize_tag

pick_chain returns a string. explain_prompt needs {tag} in a dict. normalize_tag strips spaces, angle brackets, and lowercases — no extra prompt for that cleanup.

pick_chain output

pick_chain returns:
" <A> "   or   "<a>"

Extra spaces, brackets, wrong case

After normalize_tag

RunnableLambda returns:
{"tag": "a"}

{"tag": "a"} for explain_prompt

String in from pick_chain, dict out for explain_prompt.

The normalize_tag function

The normalize_tag function

def normalize_tag(raw: str) -> dict:
    clean = raw.strip().strip("<>").lower()
    return {"tag": clean}

# In the chain:
RunnableLambda(normalize_tag)
Input type and return type must match what the previous and next steps expect.

The chain line

chain = pick_chain | RunnableLambda(normalize_tag) | explain_prompt | model | parser

Input {"feature": "links"} → pick_chain returns a string → normalize_tag returns {"tag": "a"} → explain_prompt returns the final explanation string.

The demo script

runnable_lambda_demo.py runs the chain for links and images.

runnable_lambda_demo.py
"""runnable_lambda_demo.py"""
def normalize_tag(raw: str) -> dict: …
chain = pick_chain | RunnableLambda(normalize_tag) | explain_prompt | model | parser
explanation = chain.invoke({"feature": feature})

Download the code

runnable_lambda_demo.py

pick → normalize_tag → explain

Download .py
Save into your langchain-course folder. Needs venv, .env, and packages from Project Setup.

Run it

Activate the venv from Project Setup, then:

python runnable_lambda_demo.py
PowerShell — (.venv) active
(.venv) PS C:\projects\langchain-course> python runnable_lambda_demo.py
Feature: links
Explanation: The <a> tag creates a hyperlink to another page or resource.
Feature: images
Explanation: The <img> tag embeds an image into the page.
normalize_tag runs between pick and explain — no extra print from that step.

When to pick RunnableLambda

  • One step returns a string, the next needs a dict — normalize_tag turns pick output into {tag}.
  • Fix or format model text in Python instead of asking the model again.
  • Official reference: Run arbitrary functions.

What's Next

Next: Fallbacks, Retries & Streaming — .stream(), .with_retry(), .with_fallbacks().