# LangChain Tutorial for Beginners

URL: https://aiseason.tech/langchain-tutorial

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.

| Fact | Value |
| --- | --- |
| 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](https://aiseason.tech/rag-ai-agents).

- **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](https://aiseason.tech/langchain-vs-langgraph).
- **Skip frameworks at first** if you have never written an agent loop by hand — do [the plain-Python agent tutorial](https://aiseason.tech/how-to-build-an-ai-agent) 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`).

```bash
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.

```bash
OPENAI_API_KEY=your-key-here
```

### 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.

```python
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)
```

> 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.

```python
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}.")
```

### 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.

```python
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)
```

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.

```python
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)
```

### 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"]`.

```python
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"])
```

### 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 skill | Why it matters | Guide |
| --- | --- | --- |
| RAG | Answer from your own documents with citations | [RAG for AI agents](https://aiseason.tech/rag-ai-agents) |
| LangGraph | Branching, retries, long-running state and human approval | [LangGraph tutorial](https://aiseason.tech/langgraph-tutorial) · [LangChain vs LangGraph](https://aiseason.tech/langchain-vs-langgraph) |
| MCP | Connect agents to tools and data through a standard protocol | [MCP guide](https://aiseason.tech/mcp-course) |
| Frameworks | When to pick LangChain, LangGraph or something else | [AI agent frameworks compared](https://aiseason.tech/ai-agent-frameworks) |
| The full path | Every skill in order, with a project per stage | [AI agents roadmap](https://aiseason.tech/ai-agents-learning-roadmap) |

If you would rather learn this live, the [AI Season bootcamp](https://aiseason.tech/) 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.

---

_Last updated: 2026-09-27. Canonical page: https://aiseason.tech/langchain-tutorial. Source: AI Season (https://aiseason.tech/)._
