+91 99301 12627
Generative AI & LLM

LangChain Tutorial for Beginners: Build Your First LLM App

By Mehul Prajapati

Metal chain links representing chained LLM steps in LangChain
On this page

Short answer: LangChain is a Python (and JavaScript) framework for building applications with large language models. Its building blocks are chat models, prompt templates, output parsers, retrievers (for RAG) and tools, which you connect into chains using the pipe (|) syntax. In this tutorial you’ll install LangChain, build a simple prompt chain, add structured output, and create a basic RAG pipeline. For complex, stateful agents, LangChain’s sister library LangGraph is the usual next step.

Key takeaways

  • LangChain standardises how you call models, prompts, retrievers and tools.
  • Chains are composed with the pipe operator: prompt | model | parser.
  • RAG in LangChain = loader → splitter → embeddings → vector store → retriever.
  • Use LangGraph for multi-step, stateful agents.

Core concepts

Component What it does
Chat model Wraps an LLM provider or local model behind one interface
Prompt template Reusable prompt with variables
Output parser Turns model output into strings, JSON or Python objects
Document loader Reads PDFs, web pages, CSVs and more
Text splitter Splits documents into chunks
Vector store + retriever Stores embeddings and fetches relevant chunks
Tools Functions an LLM can call (search, calculator, APIs)

Step 1: Install

pip install langchain langchain-openai langchain-community langchain-text-splitters faiss-cpu

LangChain splits integrations into separate packages (for example langchain-openai); install the one for your model provider and set its API key as an environment variable. Package names and APIs evolve, so check the current documentation.

Step 2: Your first chain

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

model = ChatOpenAI(model='your-model-name', temperature=0)
prompt = ChatPromptTemplate.from_messages([
    ('system', 'You are a helpful career counsellor for IT students.'),
    ('user', 'Suggest 3 beginner projects for someone learning {topic}.')
])

chain = prompt | model | StrOutputParser()
print(chain.invoke({'topic': 'machine learning'}))

Step 3: Structured output

from pydantic import BaseModel

class Course(BaseModel):
    name: str
    duration_weeks: int
    skills: list[str]

structured = model.with_structured_output(Course)
result = structured.invoke('Extract: Python course, 8 weeks, covers Pandas and SQL.')
print(result)

Step 4: A simple RAG pipeline

from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import FAISS
from langchain_core.runnables import RunnablePassthrough

docs = PyPDFLoader('handbook.pdf').load()
chunks = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150).split_documents(docs)
retriever = FAISS.from_documents(chunks, OpenAIEmbeddings()).as_retriever(search_kwargs={'k': 4})

rag_prompt = ChatPromptTemplate.from_template(
    'Answer only from the context. If unsure, say you do not know.\n\nContext:\n{context}\n\nQuestion: {question}'
)
format_docs = lambda ds: '\n\n'.join(d.page_content for d in ds)

rag_chain = ({'context': retriever | format_docs, 'question': RunnablePassthrough()}
             | rag_prompt | model | StrOutputParser())
print(rag_chain.invoke('What are the batch timings?'))

Go deeper: build a PDF chatbot using RAG, chunking strategies and hybrid search.

Step 5: Tools and agents

LangChain lets you define Python functions as tools that a model can choose to call. For agents that loop, branch, keep state or need human approval, use LangGraph. Background: What are AI agents?

Best practices

  • Keep API keys in environment variables, never in code
  • Set temperature=0 for factual or extraction tasks
  • Log prompts, responses and latency for debugging
  • Build a small evaluation set and test changes against it
  • Pin package versions in requirements.txt

Frequently asked questions

Is LangChain necessary to build LLM apps?

No. You can call model APIs directly. LangChain helps when you need many integrations, RAG components or a standard way to compose steps.

LangChain vs LlamaIndex?

Both support RAG. LlamaIndex focuses on data indexing and retrieval; LangChain is a broader framework for chains, tools and agents. Many teams use either successfully.

Can I use open-source models?

Yes. LangChain integrates with local and hosted open-source models, for example via Hugging Face.

Conclusion

This LangChain tutorial covered the essentials: models, prompts, parsers, chains, structured output and a simple RAG pipeline. Build a small app with your own documents next, then move to LangGraph when you need agents.

Build LangChain and LangGraph apps hands-on in our Generative AI App Developer course.

Learn with Mehul Prajapati in Borivali West

At Mehul Prajapati’s institute, you get 100% practical, hands-on training by industry experts with a minimum of 5+ years of experience, plus job-oriented programmes with placement support. Weekday and weekend batches are available, with multiple 2-hour slots between 8 am and 6 pm.

Address: 12th Floor, 1214, Gold Crest Business Centre, LT Rd, Above Westside Showroom, Borivali West, Mumbai, Maharashtra 400092
Call: +91 99301 12627 / +91 96645 45072

Visit the centre or call us to choose the right course and batch and to know the current fee structure.