LangChain Tutorial for Beginners

A hands-on LangChain tutorial for beginners: install it, call a model, give it tools, turn it into an agent, add memory and get structured output — with runnable Python at every step. It is written for students in Pakistan and India who know basic Python and want to build real AI agents, not just read about them.

By Abdul Rahman Azam, founder of AI Season · Updated

Learn LangChain live with us →

Key facts

You need Basic Python, a terminal and an API key for any chat model that supports tool calling
LangChain version 1.x — agents are built with create_agent
You will build A tool-using agent with memory and structured output
Time About 60–90 minutes
Next step LangGraph, RAG and MCP — see the links at the end

What LangChain is, and when you need it

LangChain is an open-source Python (and JavaScript) framework for building applications on top of large language models. It gives you one interface for many model providers, a standard way to describe tools, ready-made agents that call those tools in a loop, and integrations for the document loaders, vector stores and retrievers used in RAG.

  • Use LangChain when you want to switch models without rewriting code, wire tools to a model quickly, or reuse its integrations.
  • Use LangGraph (which LangChain agents run on) when you need explicit control: branching, retries, long-running state and human approval. See LangChain vs LangGraph.
  • Skip frameworks at first if you have never written an agent loop by hand — do the plain-Python agent tutorial first, then come back. LangChain is much easier once you know what it automates.

Step 1: Install LangChain

Create a project folder and a virtual environment, then install LangChain plus the integration package for your model provider. This tutorial uses OpenAI; for other providers install their package instead (for example langchain-anthropic or langchain-google-genai).

mkdir langchain-tutorial && cd langchain-tutorial
python -m venv .venv
# Windows: .venv\Scripts\activate   ·   macOS/Linux: source .venv/bin/activate
pip install -U langchain langchain-openai python-dotenv

Put your key in a .env file and never commit it to GitHub.

OPENAI_API_KEY=your-key-here
.env

Step 2: Call a model with init_chat_model

init_chat_model creates a chat model from a provider:model string, so changing providers later is a one-line change.

from dotenv import load_dotenv
from langchain.chat_models import init_chat_model

load_dotenv()
model = init_chat_model("openai:gpt-4o-mini", temperature=0)

reply = model.invoke("Explain an AI agent in one sentence.")
print(reply.content)
step2.py

If this fails, fix it before going further: most errors at this stage are a missing key, an inactive virtual environment or a model name your account cannot use.

Step 3: Give the model a tool

A tool is a normal Python function with the @tool decorator. LangChain reads the function name, type hints and docstring and turns them into the description the model sees — so the docstring is not decoration, it is how the model decides when to call the tool.

from langchain.tools import tool

# Demo data so the tutorial runs offline. Swap in a real weather API later.
DEMO_WEATHER = {"karachi": "33°C, humid", "lahore": "36°C, sunny", "delhi": "35°C, hazy", "mumbai": "30°C, rain"}

@tool
def get_weather(city: str) -> str:
    """Get the current weather for a city in Pakistan or India."""
    return DEMO_WEATHER.get(city.lower(), f"No data for {city}.")
tools.py

Step 4: Build the agent with create_agent

create_agent wires the model and tools into the agent loop: the model reads the question, decides whether to call a tool, LangChain runs the tool and sends the result back, and the loop repeats until the model answers.

from dotenv import load_dotenv
from langchain.agents import create_agent
from tools import get_weather

load_dotenv()
agent = create_agent(
    model="openai:gpt-4o-mini",
    tools=[get_weather],
    system_prompt="You are a helpful assistant. Use tools for facts; never guess the weather.",
)

result = agent.invoke(
    {"messages": [{"role": "user", "content": "Is it hotter in Lahore or Delhi right now?"}]}
)
print(result["messages"][-1].content)
agent.py

Print all of result["messages"] instead of only the last one and you will see the whole loop: your question, the model's two tool calls, the tool results and the final answer. Reading that trace is the fastest way to debug an agent.

Step 5: Add memory

Models are stateless. To let the agent remember earlier turns, give it a checkpointer and reuse the same thread_id for one conversation. InMemorySaver keeps history in RAM, which is fine for learning; production apps use a database-backed checkpointer.

from langgraph.checkpoint.memory import InMemorySaver

agent = create_agent(
    model="openai:gpt-4o-mini",
    tools=[get_weather],
    checkpointer=InMemorySaver(),
)
config = {"configurable": {"thread_id": "student-1"}}

agent.invoke({"messages": [{"role": "user", "content": "I live in Karachi."}]}, config)
result = agent.invoke({"messages": [{"role": "user", "content": "What's the weather where I live?"}]}, config)
print(result["messages"][-1].content)
memory.py

Step 6: Get structured output

When your code needs data rather than prose, pass a Pydantic model as response_format. The agent still uses its tools, and the validated object arrives in result["structured_response"].

from pydantic import BaseModel, Field

class WeatherReport(BaseModel):
    city: str = Field(description="City name")
    summary: str = Field(description="One-line weather summary")
    good_for_outdoor_class: bool

agent = create_agent(
    model="openai:gpt-4o-mini",
    tools=[get_weather],
    response_format=WeatherReport,
)
result = agent.invoke({"messages": [{"role": "user", "content": "Check Mumbai for an outdoor class."}]})
print(result["structured_response"])
structured.py

Common beginner mistakes

  • Vague tool docstrings — the model cannot call a tool well if the description does not say what it does and when to use it.
  • Copying old tutorials — many posts use pre-1.0 APIs such as initialize_agent or AgentExecutor. In LangChain 1.x, start from create_agent.
  • No limits or guardrails — an agent with powerful tools needs step limits, allow-lists and human approval for risky actions.
  • Skipping evaluation — keep a small set of test questions and re-run them whenever you change the prompt, model or tools.
  • Committing API keys — keep keys in .env and add it to .gitignore before your first commit.

Where to go next

Next skillWhy it mattersGuide
RAGAnswer from your own documents with citationsRAG for AI agents
LangGraphBranching, retries, long-running state and human approvalLangChain vs LangGraph
MCPConnect agents to tools and data through a standard protocolMCP guide
FrameworksWhen to pick LangChain, LangGraph or something elseAI agent frameworks compared
The full pathEvery skill in order, with a project per stageAI agents roadmap

If you would rather learn this live, the AI Season bootcamp teaches LangChain, LangGraph, RAG, MCP and deployment in 12 live sessions over 6 weeks — explained in Urdu, easy to follow for Hindi speakers, coded in English. Cohort 02 starts 1st January 2027.

Frequently asked questions

Is LangChain good for beginners?

Yes, once you know basic Python. Start with a model call, then one tool, then create_agent. It helps to build one agent loop by hand first so you understand what LangChain automates.

Should I learn LangChain or LangGraph first?

Start with LangChain's create_agent to get a working agent quickly, then learn LangGraph when you need branching, retries, long-running state or human approval. LangChain agents run on LangGraph, so the skills carry over.

Is LangChain free?

The LangChain library is open source and free. You pay only for the model you call — or nothing if you run a local model or use a provider's free tier.

Can I use LangChain without OpenAI?

Yes. init_chat_model supports many providers, including Anthropic, Google and local models, as long as you install the matching integration package and the model supports tool calling.

Is there a LangChain course in Urdu or Hindi?

AI Season teaches LangChain, LangGraph, RAG and MCP live in Urdu and English — easy to follow for Hindi speakers — over 6 weeks, with code in English and a project in every module.