Quick Answer: Install LangChain with
pip install langchain langchain-openai, define your tools, create a ReAct agent, and invoke it — you can have a working AI agent in under 15 minutes.
LangChain is the most popular framework for building AI agents in Python, with over 38 million monthly PyPI downloads. This LangChain tutorial walks you through building your first agent from scratch — no machine learning experience required, just basic Python.
By the end, you'll have a working agent that reasons about problems, calls external tools, and returns structured answers. If you're building AI agents for your team, platforms like cowork.ink can help you orchestrate and deploy them at scale.
A ReAct agent that can search the web, do math, and answer multi-step questions — the same pattern used in production AI systems.
What Is LangChain and Why Use It?
LangChain is an open-source Python framework that makes it easy to build applications powered by large language models (LLMs). Instead of writing raw API calls, LangChain gives you composable building blocks — prompts, chains, tools, memory, and agents — that snap together.
Here's why developers choose LangChain over direct API calls:
- Abstraction over LLM providers — switch between OpenAI, Anthropic, Google, or open-source models with one line of code
- Built-in agent patterns — the ReAct loop, tool calling, and planning are handled for you
- Rich tool ecosystem — web search, calculators, databases, APIs, and hundreds of community integrations
- Memory management — conversation history, summarization buffers, and persistent storage
- Production-ready — LangChain's agent runtime now runs on LangGraph, a battle-tested orchestration engine
| Feature | Direct API Calls | LangChain |
|---|---|---|
| Model switching | Rewrite code per provider | Change one class |
| Tool integration | Build from scratch | Plug-and-play |
| Agent loops | Manual implementation | Built-in ReAct pattern |
| Memory | DIY state management | Managed buffers |
| Observability | Custom logging | LangSmith integration |
Prerequisites
Before starting this LangChain tutorial, make sure you have:
- Python 3.9 or later installed (python.org)
- An OpenAI API key (or any supported LLM provider)
- Basic Python knowledge — variables, functions, and pip
- A terminal or IDE — VS Code, PyCharm, or a Jupyter notebook all work
You can follow this tutorial with any LangChain-supported model. We use OpenAI as the example, but the code works with Anthropic, Google Gemini, or local models via Ollama.
Step 1 — Install LangChain
Create a virtual environment and install the required packages:
python -m venv langchain-env
source langchain-env/bin/activate # Windows: langchain-env\Scripts\activate
pip install langchain langchain-openai langchain-community
The langchain package is the core framework. langchain-openai adds the OpenAI integration, and langchain-community includes community tools like web search.
Set your API key as an environment variable:
export OPENAI_API_KEY="sk-your-key-here"
Verify the installation:
import langchain
print(langchain.__version__)
Step 2 — Create Your First Chain
Before building an agent, let's start with a simple chain — the fundamental building block in LangChain. A chain connects a prompt template to an LLM:
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
# Initialize the model
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
# Create a prompt template
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant that explains concepts simply."),
("human", "{input}")
])
# Combine into a chain using the pipe operator
chain = prompt | llm
# Run it
response = chain.invoke({"input": "What is an AI agent?"})
print(response.content)
The | (pipe) operator is LangChain's way of composing components. Data flows left to right — from prompt to model. This is called LangChain Expression Language (LCEL).
Step 3 — Define Custom Tools
Tools are what turn a plain LLM into an agent. A tool gives your model the ability to take actions — search the web, query a database, run calculations, or call external APIs.
Here's how to define custom tools:
from langchain_core.tools import tool
@tool
def multiply(a: float, b: float) -> float:
"""Multiply two numbers together."""
return a * b
@tool
def get_word_count(text: str) -> int:
"""Count the number of words in a text string."""
return len(text.split())
# LangChain also has built-in tools
from langchain_community.tools import DuckDuckGoSearchRun
search = DuckDuckGoSearchRun()
The @tool decorator automatically converts your function into a LangChain tool. The docstring becomes the tool description that the LLM reads to decide when to use it — so write clear, specific descriptions.
The LLM decides which tool to call based entirely on the tool's name and description. Vague descriptions like "does stuff" will confuse the agent. Be specific: "Multiply two numbers together and return the result."
Step 4 — Build a ReAct Agent
Now combine everything into an agent. The ReAct pattern (Reasoning + Acting) is the default and most reliable agent architecture in LangChain:
from langchain_openai import ChatOpenAI
from langchain.agents import create_react_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate
# 1. Initialize the model
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
# 2. Collect your tools
tools = [multiply, get_word_count, search]
# 3. Create the agent with tool binding
agent = llm.bind_tools(tools)
LangChain's modern API uses bind_tools() to attach tools directly to the model. The model then uses native function calling (not text parsing) to invoke tools reliably.
For a full agent loop with automatic tool execution, use AgentExecutor or the newer LangGraph-based approach:
from langgraph.prebuilt import create_react_agent
# Create a complete ReAct agent with LangGraph runtime
agent_executor = create_react_agent(llm, tools)
# Run the agent
result = agent_executor.invoke({
"messages": [("human", "Search for the population of Tokyo and multiply it by 2")]
})
print(result["messages"][-1].content)
Here's what happens under the hood:
- Reason — the LLM reads the question and decides it needs to search first
- Act — it calls the
searchtool with "population of Tokyo" - Observe — it reads the search result (approximately 14 million)
- Reason — it decides to call
multiplynext - Act — it calls
multiply(14000000, 2) - Observe — it gets 28,000,000
- Answer — it formats and returns the final response
Step 5 — Add Memory to Your Agent
A stateless agent forgets everything between calls. To build conversational agents, you need memory:
from langgraph.prebuilt import create_react_agent
from langgraph.checkpoint.memory import MemorySaver
# Create an agent with memory
memory = MemorySaver()
agent = create_react_agent(llm, tools, checkpointer=memory)
# First message
config = {"configurable": {"thread_id": "user-123"}}
agent.invoke(
{"messages": [("human", "My name is Alice")]},
config=config
)
# Second message — the agent remembers
result = agent.invoke(
{"messages": [("human", "What's my name?")]},
config=config
)
print(result["messages"][-1].content)
# Output: "Your name is Alice!"
The MemorySaver checkpointer persists conversation state across invocations. The thread_id groups messages into separate conversations — essential when building multi-user applications.
Step 6 — Handle Errors and Edge Cases
Production agents need guardrails. Here are the patterns that matter:
from langchain_core.tools import tool
from langchain_core.runnables import RunnableConfig
@tool
def divide(a: float, b: float) -> str:
"""Divide a by b. Returns an error message if b is zero."""
if b == 0:
return "Error: Cannot divide by zero."
return str(a / b)
Common pitfalls and how to avoid them:
- Infinite loops — set
max_iterationson your agent (default is 15 in LangGraph) - Tool errors — always return error messages as strings instead of raising exceptions
- Token limits — use
trim_messagesto keep conversation history within context windows - Hallucinated tool calls — write precise tool descriptions and validate inputs
LLM costs add up fast when agents loop. Always set max_iterations and monitor token usage. A runaway agent can burn through your API budget in minutes.
Choosing the Right LangChain Components
LangChain's ecosystem has grown large. Here's what to use when:
| Component | Use When | Skip When |
|---|---|---|
| LangChain | Simple agents, chains, RAG | Complex multi-agent workflows |
| LangGraph | Stateful workflows, branching logic | Quick prototypes |
| LangSmith | Debugging, evaluation, monitoring | Just getting started |
| LangServe | Deploying agents as APIs | Using your own FastAPI |
| LCEL (pipes) | Composing prompt → model → parser | Single LLM call |
If you're comparing LangChain with other frameworks, our CrewAI vs LangChain comparison breaks down the trade-offs for multi-agent use cases.
From Tutorial to Production
Building a working agent is step one. Deploying it for a team is where things get interesting. Here's the path:
- Local prototype — what you just built
- Add observability — connect LangSmith for tracing and debugging
- Deploy as an API — wrap your agent with FastAPI or LangServe
- Scale to a team — use cowork.ink to orchestrate agents across your engineering workflow, with shared context and team-wide visibility
Whether you're building AI agents from scratch, following our Python agent tutorial, or chaining together existing tools, LangChain gives you the foundation. The framework handles the plumbing so you can focus on what your agent actually does.
Get Started
You now have everything you need to build your first LangChain agent. The complete code from this tutorial fits in a single Python file — clone it, swap in your API key, and start experimenting.
For teams ready to move beyond prototypes, cowork.ink lets you deploy, monitor, and collaborate on AI agents from a shared workspace — no infrastructure setup required.