AI Hints
Home›LangChain Tutorial›Runnables
LangChain · Lesson 20 of 120

RunnableLambda

Your own steps.

⏱ 2 min read▶ Video at 20:47🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

Sometimes a chain needs a step that's just normal Python. Cleaning text, counting words, or formatting a result. Runnable lambda wraps any function, so it can sit in a chain.

RunnableLambda
From the video: RunnableLambda
  • Plain Python steps
  • Clean, count, format
  • Wrap with RunnableLambda

A function in a chain

We write a small function that turns text to upper case, and counts its words. Runnable lambda wraps it, and we pipe it after the parser. Run it. The model's sentence flows into our function, which returns a dictionary. In fact, if you pipe a plain function, LangChain wraps it for you automatically.

lambda.pypython
from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnableLambda

def shout(text):
    return {"text": text.upper(), "words": len(text.split())}

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
prompt = ChatPromptTemplate.from_template("One short sentence about {topic}.")
chain = prompt | model | StrOutputParser() | RunnableLambda(shout)

print(chain.invoke({"topic": "libraries"}))
Output
{'text': 'LIBRARIES ARE QUIET SANCTUARIES THAT HOLD THE BOUNDLESS UNIVERSE OF HUMAN
KNOWLEDGE WITHIN THEIR WALLS.', 'words': 15}

Good uses

Runnable lambdas are perfect for small glue steps. Cleaning user input before the prompt. Reshaping data between steps. Looking something up in a dictionary or database. And formatting the final answer. Keep them small, with one job each.

keyvalue
Beforeclean the input
Betweenreshape data
Lookupsdicts, databases
Afterformat the answer

Summary

Runnable lambda turns any function into a chain step, and plain functions are wrapped automatically. Next, running steps side by side.

Key takeaways
  • RunnableLambda(fn)
  • Or just pipe a function
  • Small glue steps
Next up: RunnableParallel — side by side