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.
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_modelfrom langchain_core.prompts import ChatPromptTemplatefrom langchain_core.output_parsers import StrOutputParserfrom langchain_core.runnables import RunnableLambdadef 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}
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.