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
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
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)The chain line
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.
Download the code
runnable_lambda_demo.py
pick → normalize_tag → explain
langchain-course folder. Needs venv, .env, and packages from Project Setup.Run it
Activate the venv from Project Setup, then:
python runnable_lambda_demo.pyWhen 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().