Generative AIby Dhruv Narang

1. Common Types of Runnables

LangChain has many kinds of runnables. These are the four you will use most. You already used the first one: the pipe makes a RunnableSequence.

RunnableWhat it does
RunnableSequenceRuns steps one after another. You make it with |.
RunnableLambdaYour own Python function as a step.
RunnablePassthroughGives the input back unchanged.
RunnableParallelGives the same input to many branches at once. The result is a dict.
There are more. RunnableBranch (if / else), RunnableWithFallbacks (a backup model) and RunnableWithMessageHistory (chat memory) are some. Look at the docs when you need them.

2. RunnableLambda: Your Own Function as a Step

Sometimes you need a step the model cannot do: make the text uppercase, count the words. Write it as a plain Python function and put it in the pipe, like any other step.

The idea. A model cannot count words or be sure of capital letters. A Python function can. RunnableLambda turns your function into a step, so it fits in the pipe like the prompt, the model and the parser.
flowchart LR
  START(["START"]) --> PR["prompt"] --> M["model"] --> PA["parser"] --> F1["make_uppercase<br/>your function"] --> F2["word_counter<br/>your function"] --> END(["END"])
  class START,END term
  class PR,M,PA step
  class F1,F2 fn
classDef term fill:#0e3b3a,stroke:#0e3b3a,color:#ffffff,font-weight:bold
classDef step fill:#d4ecea,stroke:#2a7a79,color:#0e3b3a
classDef fn fill:#fbe5dc,stroke:#c9583a,color:#7a2e1a
classDef mint fill:#e3f5ee,stroke:#4aa58a,color:#14463a
The code. Here make_uppercase and word_counter_runnable are two functions of ours. The next section shows how they are written. The rest is the chain you know.
complete_chain = prompt | model | parser | make_uppercase | word_counter_runnable

res = complete_chain.invoke({"topic":"meditaiton"})
print(res)
 Example
You give{"topic": "meditaiton"}. The prompt asks the model: give 3 benefits of this topic in 1 short sentence.
The model alone saysMeditation reduces stress, sharpens focus, and strengthens emotional resilience.
print(res) showsMEDITATION REDUCES STRESS, SHARPENS FOCUS, AND STRENGTHENS EMOTIONAL RESILIENCE.
[Total Words : 9 ]
The first function made it capital. The second added the word count.
Example answer. Yours will be different.
The rule for your function. It takes one input (the output of the step before it) and returns one output (the input of the step after it).
A real example: hide private data. A customer writes a message with an email in it. You should not send the email to the model. Put a function before the prompt. It changes the email to a short note.
You give{"msg": "My order is late. Contact me at rahul@gmail.com"}
The model getsReply politely to this customer message: My order is late. Contact me at [email hidden]
Why a function? This is a plain job for code, not for a model. A function does it the same way every time, and the model never sees the real email.
Where else it is used in real projects. Each function takes the answer and gives back a changed answer.
You want toInputOutput
Hide private datarahul@gmail.com[email hidden]
Take a number out of the answerRating: 8/108
Clean the answer```json {"a": 1} ```{"a": 1}
Stop an empty answer""an error: the answer is empty

3. Two Ways to Write It

Put @chain above the function, or wrap the function with RunnableLambda. Both give you a RunnableLambda. Pick a tab.

from langchain_core.runnables import chain

@chain
def make_uppercase(text : str ) -> str:
    """ A custom Python Function that turns AI Output into UpperCase"""
    return text.upper()from langchain_core.runnables import RunnableLambda

def count_words(text :str) -> str:
    """ A Custom Python Function that counts words"""
    words = len(text.split())
    return f"{text}\n[Total Words : {words} ]"

word_counter_runnable = RunnableLambda(count_words)
Add @chain above the function. The function itself becomes a runnable.Keep the function as it is and wrap it with RunnableLambda.

4. RunnablePassthrough: Give the Input Back

Definition

RunnablePassthrough is a step that gives back exactly what it gets.

The problem. Most steps change their input. simple_chain gets {'topic': 'cloud computing'} and gives back only an explanation. The topic is gone. You have the answer, but not what it was about.
The fix. RunnablePassthrough lets the input go through untouched. You keep a copy of the original input and use it later. Think of a photocopy: the form goes on, and you keep a copy.
flowchart LR
  I(["Input<br/>topic: cloud computing"]) --> PT["RunnablePassthrough()"] --> O(["Output<br/>topic: cloud computing"])
  class I,O term
  class PT fn
classDef term fill:#0e3b3a,stroke:#0e3b3a,color:#ffffff,font-weight:bold
classDef step fill:#d4ecea,stroke:#2a7a79,color:#0e3b3a
classDef fn fill:#fbe5dc,stroke:#c9583a,color:#7a2e1a
When do you need the original input? Whenever a later step, or you, need what the user first asked.
CaseWhy the original input is needed
Show it with the answerIf you run many topics, each answer is shown next to its topic. This is the next section.
Use it twice (RAG)The question is used first to search the documents, and again in the prompt to ask the model. One copy goes to the search, one copy is kept.
Use it in a later stepA step at the end can use the original input and the new answer together.
Why not a normal variable? In a small script a variable is enough: topic = ... and print it later. But inside a chain, each step gets only the output of the step before it. A variable outside cannot reach a step in the middle.
It is never used alone. On its own it only gives the input back, which is of no use. It is always one branch inside a dict or a RunnableParallel, next to other steps. One branch keeps the copy while the other steps work. The next section shows this.
A dict is a RunnableParallel. A dict {...} written inside a chain becomes a RunnableParallel by itself. You do not have to write the name.

5. RunnableParallel: Many Branches at Once

RunnableParallel gives the same input to many branches at once and returns a dict. One of the branches can be RunnablePassthrough.

The idea. One input, many answers. RunnableParallel sends the same input to every branch at the same time and collects the answers in one dict, one key for each branch.
flowchart LR
  I(["Input<br/>topic: cloud computing"]) --> S["simple_chain<br/>for a 5-year-old"]
  I --> X["expert_chain<br/>for a senior engineer"]
  S -->|simple_explanation| O(["One dict"])
  X -->|expert_explanation| O
  class I,O term
  class S,X step
classDef term fill:#0e3b3a,stroke:#0e3b3a,color:#ffffff,font-weight:bold
classDef step fill:#d4ecea,stroke:#2a7a79,color:#0e3b3a
classDef fn fill:#fbe5dc,stroke:#c9583a,color:#7a2e1a
classDef mint fill:#e3f5ee,stroke:#4aa58a,color:#14463a
Add a third branch. RunnablePassthrough() from the last section is one more branch. It gives the input back, so the original input is in the result too.
flowchart LR
  I(["Input<br/>topic: cloud computing"]) --> S["simple_chain"]
  I --> X["expert_chain"]
  I --> PT["RunnablePassthrough()<br/>input, unchanged"]
  S -->|simple_explanation| O(["One dict"])
  X -->|expert_explanation| O
  PT -->|orignal_topic| O
  class I,O term
  class S,X step
  class PT fn
classDef term fill:#0e3b3a,stroke:#0e3b3a,color:#ffffff,font-weight:bold
classDef step fill:#d4ecea,stroke:#2a7a79,color:#0e3b3a
classDef fn fill:#fbe5dc,stroke:#c9583a,color:#7a2e1a
classDef mint fill:#e3f5ee,stroke:#4aa58a,color:#14463a
The code. simple_chain and expert_chain are normal chains, prompt | model | parser, with a different prompt each. The dictionary is the new part: the key is the name of the answer, the value is the runnable that makes it.
parallel_chain = RunnableParallel(
    {
        "simple_explanation" : simple_chain,
        "expert_explanation" : expert_chain,
        "orignal_topic" : RunnablePassthrough()
    }
)

result = parallel_chain.invoke({"topic":"cloud computing"})

print(result["simple_explanation"])
print(result["expert_explanation"])
print(result["orignal_topic"])
You get
Cloud computing is like a big, invisible toy box in the sky where you can put your drawings and games and play with them from any computer or tablet, just like magic!
Cloud computing is a model for delivering on-demand, scalable, pay-per-use computing resources—such as virtual machines, containers, storage, and managed services—via a globally distributed network of remote servers, abstracting physical infrastructure to enable rapid deployment, elasticity, and high availability.
{'topic': 'cloud computing'}
Example answers. Yours will be different.
Why use it? The branches do not need each other, so we do not wait for one before we start the next. One invoke gives many answers, and you read each one by its key.

Code
04_custom_runnables.py04_custom_runnables.py · 34 linesShow code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from dotenv import load_dotenv

load_dotenv()


from langchain.chat_models import init_chat_model
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import chain ,RunnableLambda
from langchain_core.prompts import ChatPromptTemplate
model = init_chat_model("mistralai:open-mistral-nemo")
parser = StrOutputParser()

"""Your own Python function as a step: @chain or RunnableLambda"""
@chain
def make_uppercase(text : str ) -> str:
    """ A custom Python Function that turns AI Output into UpperCase"""
    return text.upper()

def count_words(text :str) -> str:
    """ A Custom Python Function that counts words"""
    words = len(text.split())
    return f"{text}\n[Total Words : {words} ]"

word_counter_runnable = RunnableLambda(count_words)


prompt = ChatPromptTemplate.from_template("Give 3 benefits of {topic} in 1 short sentance.")

complete_chain = prompt | model | parser | make_uppercase | word_counter_runnable

res = complete_chain.invoke({"topic":"meditaiton"})
print(res)
05_parallel_and_passthrough.py05_parallel_and_passthrough.py · 39 linesShow code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from dotenv import load_dotenv
load_dotenv()

from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnableParallel , RunnablePassthrough
from langchain.chat_models import init_chat_model


model = init_chat_model("mistralai:open-mistral-nemo")

parser = StrOutputParser()


prompt_simple = ChatPromptTemplate.from_template("Explain {topic} to a  5-year old in 1 sentence ")

simple_chain = prompt_simple | model | parser

prompt_expert = ChatPromptTemplate.from_template("Explain {topic} to a Senior Engineer in 1 sentence.")
expert_chain = prompt_expert | model | parser


"""RunnableParallel: same input to all branches at once; RunnablePassthrough: input unchanged"""
parallel_chain = RunnableParallel(
    {
        "simple_explanation" : simple_chain,
        "expert_explanation" : expert_chain,
        "orignal_topic" : RunnablePassthrough()
    }
)


result = parallel_chain.invoke({"topic":"cloud computing"})

print(result["simple_explanation"])
print("--------------------------")
print(result["expert_explanation"])
print("--------------------------")
print(result["orignal_topic"])