Course Content
LangChain Mastery
7 sections · 109 lessons
What is a chain in LangChain, and how is it used in NLP?
What you need to know
The word "chain" comes from LangChain's early Chain classes, like LLMChain. Those are legacy now. Today "chain" just means a composed Runnable.
1from langchain_core.prompts import ChatPromptTemplate2from langchain_core.output_parsers import StrOutputParser34summarize = (5 ChatPromptTemplate.from_template("Summarise this ticket in one line:\n{ticket}")6 | llm7 | StrOutputParser()8)9summarize.invoke({"ticket": "App crashes when I upload a PAN card photo..."})The | operator creates a RunnableSequence. Data flows left to right: a dict goes into the prompt, a list of messages goes to the model, an AIMessage goes to the parser, and a string comes out.
What composition gives you
- One interface:
invoke,batch,stream,ainvoke,abatch,astream. - Wrappers:
.with_retry(),.with_fallbacks(),.with_config(run_name=...). - Tracing: every step appears as its own node in LangSmith.
- Streaming through the pipe: the parser streams as the model streams.
The main building blocks
| Block | What it does |
|---|---|
a | b | Run a, then b on its output |
{"x": a, "y": b} or RunnableParallel | Run a and b on the same input at the same time; return a dict |
RunnablePassthrough.assign(k=a) | Keep the input dict and add key k |
RunnableLambda(fn) | Turn any Python function into a step |
RunnableBranch | Pick a step based on a condition |
Chain or agent?
Chain
- Path fixed in code
- Predictable cost and latency
- Easy to test step by step
Agent
- Model chooses tools and order
- Cost and latency vary per request
- Needed when steps depend on what it finds
Start with a chain. Move to an agent (create_agent) or a LangGraph workflow only when the steps cannot be known in advance.
A real-life example
A support team at a Noida SaaS company receives 4,000 tickets a day. Their triage chain has four fixed steps: a prompt that asks for category and urgency, the model, a structured-output parser that returns a Triage object, and a function that writes it to the helpdesk. Because the path never changes, cost is steady at about one model call per ticket and every failure points to one step in the trace. An earlier prototype used an agent with a "classify" tool and a "save" tool; it sometimes saved before classifying and cost 2 to 3 calls per ticket. The chain was simpler, cheaper and easier to debug.
Follow-up questions to expect
- "What is LCEL?" — LangChain Expression Language: the
|syntax and Runnable primitives for composing steps declaratively. - "Can a chain have loops?" — Not naturally. For loops, retries based on output, or human approval, use LangGraph.
- "Is
LLMChaina chain?" — It was the old chain class. It is deprecated and inlangchain-classic;prompt | llmreplaces it.