Generative AIby Dhruv Narang

1. The Pipe: One Line Instead of Three

LangChain's fix: stop making a class for every job. Join any steps with one symbol.

Definition

The pipe | takes the output of the left side and gives it to the right side. This way of joining steps is called LCEL, the LangChain Expression Language.

Step 1. The three parts. Every question goes through the same three steps. Each step is an object.
from langchain_core.prompts import ChatPromptTemplate
from langchain.chat_models import init_chat_model
from langchain_core.output_parsers import StrOutputParser

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

prompt = ChatPromptTemplate.from_template("What is the capital of {state}? Answer in one short sentence.")

parser = StrOutputParser()
PartWhat it does
promptFills the blank {state} and makes the question.
modelReads the question and writes the answer.
parserTakes the text out of the model's reply.
Step 2. Join them with the pipe. The answer of the left side goes into the right side. Three steps become one object, chain.
chain = prompt | model | parser
Step 3. Run it. One invoke runs all three steps. The input is a dictionary. The key is the blank of the prompt.
res = chain.invoke({"state":"Gujarat"})
print(res)
You get
The capital of Gujarat is Gandhinagar.
Example answer. Yours will be different.
Why use the pipe? Without it you call the prompt, then the model, then the parser, and pass the result along by hand. With the pipe you write the steps once and call the chain.

2. What Is a Runnable?

Definition

A Runnable is anything in LangChain you can run with .invoke().

The name says it: Run + able = something you are able to run. The prompt, the model, the parser and the chain are all runnables, so all of them have the same methods.

These are all runnablesSo each one has
Prompt, model, parserinvoke, stream, batch
A chain made with the pipethe same three methods

Run the chain from the last section in three ways. Pick a tab.

chain = prompt | model | parser
res = chain.invoke({"state":"Gujarat"})
print(res)chain = prompt | model | parser
for chunk in chain.stream({"state":"Maharashtra"}):
    print(chunk,end="",flush=True)states_list = [
    {"state": "Gujarat"},
    {"state": "Kerala"},
    {"state": "Rajasthan"}
]

chain = prompt | model | parser
batch_result = chain.batch(states_list)

for item in batch_result:
    print(item)
You get
The capital of Gujarat is Gandhinagar.
Mumbai| is| the| capital| of| Maharashtra|.
The capital of Gujarat is Gandhinagar.
The capital of Kerala is Thiruvananthapuram.
The capital of Rajasthan is Jaipur.
One input, one full answer.The answer arrives piece by piece (the | marks the pieces). end="" keeps the pieces on one line. flush=True shows each piece on the screen at once, so you see the words appear as they are written.Many inputs in one go. You get a list back, one answer for each input, in the same order.

3. A Chain Is a Runnable Too

Because a chain is a runnable, you can use it inside another chain.

Step 1. Two chains. Same model and parser as before. chain1 writes a company name. chain2 writes a slogan for a company name.
prompt1 = ChatPromptTemplate.from_template(
    "What is a catchy company name for a business that makes {product}? Give ONLY the name in 2-3 words."
)
chain1  = prompt1 | model | parser

prompt2 = ChatPromptTemplate.from_template(
    "Write a punchy 1-line advertising slogan for a company named {company_name}."
)
chain2 = prompt2 | model | parser
Step 2. Join the two chains. chain1 is a runnable, so it can sit inside the chain. The dictionary saves its answer under the key company_name. That fills the blank {company_name} in prompt2.
chain = ({'company_name':chain1} | chain2)
Step 3. Run it. Give only the first input. chain1 runs first, then chain2.
slogan = chain.invoke({"product":"cool lightweight laptop"})
print(slogan)
You giveYou get
cool lightweight laptopNimbus Gear: Elevate Every Ride.
Electric CycleVolt Glide: Charge Ahead, Glide Forward.
Example answers. Yours will be different.
Why use it? The answer of one chain is the input of the next one, and you run both with one invoke. It is the same job as SimpleSequentialChain, with the pipe.
LangChain docsRunnable
Code
02_lcel_runnables_basic.py02_lcel_runnables_basic.py · 33 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_core.prompts import ChatPromptTemplate
from langchain.chat_models import init_chat_model
from langchain_core.output_parsers import StrOutputParser
model = init_chat_model(model="mistralai:open-mistral-nemo")

prompt = ChatPromptTemplate.from_messages(
    [("system","You are a concise geography expert. Answer in small paragraph"),
     ("human","what is captial of {state}")]
)
parser = StrOutputParser()

chain = prompt | model | parser

# res = chain.invoke({"state":"punjab"})
# print(res)

# for chunk in chain.stream({"state":"Maharashtra"}):
#     print(chunk,end="",flush=True)

states_list = [
    {"state": "Gujarat"},
    {"state": "Kerala"},
    {"state": "Rajasthan"}
]

batch_result = chain.batch(states_list)

for item in batch_result:
    print(item)
03_runnables.py03_runnables.py · 27 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
from dotenv import load_dotenv

load_dotenv()

from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from rich import print

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

prompt1 = ChatPromptTemplate.from_template(
    "What is a catchy company name for a business that makes {product}? Give ONLY the name in 2-3 words."
)
chain1  = prompt1 | model | parser

prompt2 = ChatPromptTemplate.from_template(
    "Write a punchy 1-line advertising slogan for a company named {company_name}."
)
chain2 = prompt2 | model | parser

chain = ({'company_name':chain1} | chain2)

slogan = chain.invoke({"product":"cool lightweight laptop"})
print(slogan)