AI

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 dictPromptTemplateChatModelOutputParserString / 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 LangChainUse raw SDK
RAG + agent prototypesSingle chat completion endpoint
Many third-party integrationsLatency-critical microservice
Team standardizes on LCMinimal dependencies, full control
LangSmith tracing out of boxSimple 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

PitfallWhy it hurtsFix
Deprecated APIs in tutorialsCopy-paste breaks on upgradeCheck docs version; prefer langchain-core LCEL
Over-abstraction for one callHarder debug than 10-line SDKRaw SDK for trivial endpoints
Implicit prompt injection via retrieverMalicious doc content in contextSanitize retrieved text; system guardrails
No tracing enabledBlack box failuresLangSmith or custom callbacks on chain
Giant monolithic chainsUntestable spaghettiSplit into named sub-chains with unit tests
Wrong retriever kNoise or missed contextTune 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

QuestionAnswer
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
langchainlcelpythonraglanggraph

⑧ 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