LangChain Basics
Chains, prompts, retrievers, and agents — the popular Python framework for LLM apps.
Interview tip Know: LCEL (pipe syntax), ChatModel vs LLM, RunnableSequence. Say when you'd use LangChain vs raw SDK.
① What you must know (30 sec)
LangChain is a Python/JS framework that composes LLM apps from reusable pieces: prompts, models, retrievers, parsers, and agents. LCEL (LangChain Expression Language) chains them with the pipe operator:
chain = prompt | model | parser. Ideal for RAG and agent prototypes; consider raw SDK for minimal latency microservices.Analogy: LangChain is like React for LLM apps — components and composition — whereas raw SDK is vanilla JS when you want zero dependencies.
② How it works
LCEL chain
Input dict→PromptTemplate→ChatModel→OutputParser→String / JSON
Models — ChatOpenAI, ChatAnthropic wrappers with unified .invoke()
Prompts — ChatPromptTemplate with {variables}
Retrievers — vector store .as_retriever() for RAG
Output parsers — StrOutputParser, JsonOutputParser, Pydantic
Agents — LangGraph or create_react_agent with tool binding
LangChain v0.2+ favors LCEL and langchain-core; avoid deprecated Chain classes in new code.
③ Step-by-step (hands-on)
Step 1 — Install core packages
pip install langchain langchain-openai langchain-community. Set OPENAI_API_KEY in environment.
Step 2 — Build a simple chain
from langchain_core.prompts import ChatPromptTemplate; from langchain_openai import ChatOpenAI; chain = prompt | ChatOpenAI() | StrOutputParser()
Step 3 — Invoke with dict
result = chain.invoke({"question": "What is RAG?"}) — input keys match prompt variables.
Step 4 — Add a retriever for RAG
retriever = vectorstore.as_retriever(search_kwargs={"k": 4}); use create_retrieval_chain or custom LCEL with RunnablePassthrough.
Step 5 — Stream tokens
for chunk in chain.stream({"question": "..."}): print(chunk, end="") — same chain, streaming API.
Step 6 — Move agents to LangGraph
For multi-step agents, prefer langgraph StateGraph over legacy AgentExecutor for control and checkpoints.
④ Code / config patterns
| Use LangChain | Use raw SDK |
|---|---|
| RAG + agent prototypes | Single chat completion endpoint |
| Many third-party integrations | Latency-critical microservice |
| Team standardizes on LC | Minimal dependencies, full control |
| LangSmith tracing out of box | Simple CRUD wrapper around GPT |
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser
prompt = ChatPromptTemplate.from_messages([
("system", "Answer concisely."),
("human", "{question}")
])
chain = prompt | ChatOpenAI(model="gpt-4o-mini") | StrOutputParser()
answer = chain.invoke({"question": "What is LCEL?"})⑤ Production & pitfalls
| Pitfall | Why it hurts | Fix |
|---|---|---|
| Deprecated APIs in tutorials | Copy-paste breaks on upgrade | Check docs version; prefer langchain-core LCEL |
| Over-abstraction for one call | Harder debug than 10-line SDK | Raw SDK for trivial endpoints |
| Implicit prompt injection via retriever | Malicious doc content in context | Sanitize retrieved text; system guardrails |
| No tracing enabled | Black box failures | LangSmith or custom callbacks on chain |
| Giant monolithic chains | Untestable spaghetti | Split into named sub-chains with unit tests |
| Wrong retriever k | Noise or missed context | Tune k on eval set; add reranker |
Production tips:
- Pin langchain package versions; test upgrades in staging
- Use RunnableConfig for run_name and metadata in traces
- Cache embeddings and frequent retrievals
- LangGraph checkpoints for resumable long agents
⑥ Interview / on-the-job Q&A
| Question | Answer |
|---|---|
| What is LCEL? | Pipe syntax to compose Runnables: prompt | model | parser with .invoke() and .stream(). |
| ChatModel vs LLM? | ChatModel uses message objects (system/user/assistant); legacy LLM uses plain strings. |
| LangChain vs LlamaIndex? | LangChain general composition; LlamaIndex indexing/retrieval focus. Many use both. |
| What is a retriever? | Interface that returns relevant documents for a query — wraps vector store search. |
| AgentExecutor vs LangGraph? | LangGraph offers explicit state machine, persistence, and human-in-the-loop — preferred for prod agents. |
| How debug chains? | LangSmith traces, verbose=True on older chains, or log intermediate Runnable outputs. |
⑦ Tools & ecosystem
- Core: langchain-core, langchain-openai, langchain-anthropic
- Vector: langchain-chroma, langchain-pinecone, langchain-postgres
- Agents: langgraph, langchain-community tools
- Observability: LangSmith
⑧ Revision checklist
- Using LCEL pipe syntax, not deprecated LLMChain
- ChatPromptTemplate variables match .invoke() keys
- StrOutputParser or JsonOutputParser on chain end
- Retriever k tuned on sample questions
- Package versions pinned in requirements.txt
- LangSmith or logging enabled for dev
- Agents use LangGraph for new projects
- Simple endpoints evaluated for raw SDK alternative
- Integration tests on chain with mocked model