LangChain 101: Your First Chain in 30 Minutes
LangChain gives you Python building blocks for connecting prompts, models, and output parsers into reliable AI pipelines, and your first chain takes under 30 minutes to build.
Key Takeaways
- Comprehensive strategies proven to work at top companies
- Actionable tips you can implement immediately
- Expert insights from industry professionals
If you have ever written an AI feature and thought "this is just prompt engineering glued together with string formatting," you have discovered the problem LangChain solves. LangChain provides composable Python classes for each piece of an LLM pipeline: prompts, models, parsers, retrievers, and chains. You snap them together instead of wiring raw strings.
This post gets you from pip install to a working chain in 30 minutes. No prior LangChain experience needed.
What LangChain Actually Does
LangChain is a framework with three layers. The first layer is primitives: prompt templates, chat models, and output parsers. These are the atoms. The second layer is chains: sequences of primitives connected by the pipe operator. These are the molecules. The third layer is agents and retrieval: chains that can use tools and access external knowledge. These are the cells.
You start at layer one, build a chain at layer two, and graduate to layer three once the fundamentals are solid. This post covers layers one and two.
Install the dependencies:
pip install langchain langchain-anthropic langchain-core
# Set your API key in your environment
export ANTHROPIC_API_KEY='your-key-here'
Your First Chain: Prompt, Model, Parser
The most basic LangChain chain has three parts. A PromptTemplate defines the structure of what you send to the model. A ChatModel is the LLM. An OutputParser takes the model's raw response and converts it to the data type you want.
Connect them with the pipe operator and you have a chain. Call the chain with invoke and it runs end to end.
from langchain_anthropic import ChatAnthropic
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
# 1. Define the prompt template
prompt = ChatPromptTemplate.from_messages([
('system', 'You are a helpful product analyst. Answer concisely.'),
('human', '{question}')
])
# 2. Pick a model
model = ChatAnthropic(model='claude-3-5-sonnet-20241022')
# 3. Parse the output as a plain string
parser = StrOutputParser()
# 4. Compose the chain with the pipe operator
chain = prompt | model | parser
# 5. Run it
result = chain.invoke({'question': 'What is churn rate and why does it matter?'})
print(result)
Prompt Templates: The Key to Reliable Output
Raw f-strings break the moment a variable contains curly braces or special characters. PromptTemplate handles escaping, validation, and variable injection safely. It also makes your prompts reusable across different inputs.
Use ChatPromptTemplate for multi-turn prompts and PromptTemplate for single-turn. The human/system/assistant roles map directly to how the model expects to receive context.
Prompt
"You are a product analyst specializing in SaaS metrics. Given the following raw metric data, identify the top three trends and explain each in one sentence. Format your response as a numbered list. Data: {metric_data}"
Sequential Chains: Connecting Multiple Steps
Real pipelines have multiple steps. LangChain's pipe operator chains them in sequence: the output of one step becomes the input to the next. Here is a two-step chain that first summarizes an article and then classifies its sentiment:
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_anthropic import ChatAnthropic
model = ChatAnthropic(model='claude-3-5-sonnet-20241022')
parser = StrOutputParser()
summarize_prompt = ChatPromptTemplate.from_template(
'Summarize this article in two sentences: {article}'
)
classify_prompt = ChatPromptTemplate.from_template(
'Classify the sentiment of this summary as Positive, Negative, or Neutral. '
'Reply with only the label. Summary: {summary}'
)
# Chain: article -> summary -> sentiment label
chain = (
summarize_prompt | model | parser
| (lambda summary: {'summary': summary})
| classify_prompt | model | parser
)
result = chain.invoke({'article': 'Your article text here...'})
print(result) # 'Positive', 'Negative', or 'Neutral'
This pattern composes indefinitely. Each step is independently testable, each prompt is independently editable, and the whole pipeline runs in a single invoke call.
Want to build this live with Aki?
Join a Lightning Lesson and go deeper on this topic. Browse upcoming sessions →
Aki Wijesundara
Expert team of AI professionals and career advisors with experience at top tech companies. We've helped 500+ students land internships at Google, Meta, OpenAI, and other leading AI companies.
Ready to Launch Your AI Career?
Join our comprehensive program and get personalized guidance from industry experts who've been where you want to go.
Table of Contents
Share Article
Get Weekly AI Career Tips
Join 5,000+ professionals getting actionable career advice in their inbox.
No spam. Unsubscribe anytime.